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

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

$id = $_GET['id'];

// 1. Ambil data profil lansia
$stmt = $pdo->prepare("SELECT *, TIMESTAMPDIFF(YEAR, tgl_lahir, CURDATE()) AS umur FROM lansia WHERE id_lansia = ?");
$stmt->execute([$id]);
$l = $stmt->fetch();

if (!$l) { die("Data tidak ditemukan."); }

// 2. Ambil riwayat pemeriksaan
$stmt_p = $pdo->prepare("SELECT * FROM pemeriksaan_lansia WHERE id_lansia = ? ORDER BY tgl_periksa ASC");
$stmt_p->execute([$id]);
$riwayat = $stmt_p->fetchAll();

// 3. Siapkan data untuk grafik (Tensi)
$labels = []; $systolic = []; $diastolic = [];
foreach ($riwayat as $r) {
    $labels[] = date('d/m/y', strtotime($r['tgl_periksa']));
    $tensi_split = explode('/', $r['tensi'] ?? '');
    $systolic[] = isset($tensi_split[0]) ? (int)$tensi_split[0] : 0;
    $diastolic[] = isset($tensi_split[1]) ? (int)$tensi_split[1] : 0;
}

// FUNGSI INDIKATOR WARNA
function cekStatus($nilai, $tipe, $jk = 'L') {
    if ($nilai <= 0 || empty($nilai)) return "";
    $danger = "style='color: #dc3545; font-weight: bold;'";
    if ($tipe == 'gds' && ($nilai > 200 || $nilai < 70)) return $danger;
    if ($tipe == 'asam_urat' && (($jk == 'L' && $nilai > 7) || ($jk == 'P' && $nilai > 6))) return $danger;
    if ($tipe == 'kolesterol' && $nilai > 200) return $danger;
    if ($tipe == 'imt' && ($nilai > 25 || $nilai < 18.5)) return $danger;
    return "";
}

function cekTensi($tensi) {
    if (empty($tensi)) return "";
    $parts = explode('/', $tensi);
    $sis = isset($parts[0]) ? (int)$parts[0] : 0;
    $dia = isset($parts[1]) ? (int)$parts[1] : 0;
    if ($sis >= 140 || $dia >= 90) return "style='background: #dc3545; color: white; padding: 2px 6px; border-radius: 5px;'";
    return "class='badge-tensi'";
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Detail Lansia</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 ASLI */
        .header-purple { background: #6f42c1; color: white; padding: 20px; border-bottom-left-radius: 20px; border-bottom-right-radius: 20px; }
        .card-custom { border: none; border-radius: 15px; box-shadow: 0 4px 10px rgba(0,0,0,0.05); margin-bottom: 15px; background: white; }
        .btn-periksa { background: #198754; color: white; border-radius: 10px; font-weight: bold; }
        
        .table-responsive { border-radius: 10px; overflow-x: auto; }
        table { font-size: 11px; min-width: 1300px; } 
        th { background: #f8f9fa !important; color: #666; text-transform: uppercase; padding: 12px 8px; }
        .badge-tensi { background: #e7f1ff; color: #0d6efd; font-weight: bold; padding: 5px 10px; border-radius: 8px; }
        .btn-action { padding: 4px 8px; font-size: 12px; border-radius: 8px; }
    </style>
</head>
<body>

<div class="header-purple shadow-sm">
    <div class="container d-flex align-items-center">
        <a href="lansia_index.php" class="text-white me-3 fs-4"><i class="bi bi-arrow-left"></i></a>
        <h5 class="mb-0 fw-bold">Profil Lansia</h5>
    </div>
</div>

<div class="container mt-3 pb-5">
    <div class="card card-custom p-3">
        <div class="d-flex justify-content-between align-items-start">
            <div>
                <h4 class="fw-bold mb-0" style="color:#6f42c1;"><?= strtoupper($l['nama_lansia']) ?></h4>
                <p class="text-muted mb-2"><?= $l['nik_lansia'] ?></p>
                <div class="d-flex gap-2 mb-2">
                    <span class="badge bg-light text-dark border"><?= $l['umur'] ?> Tahun</span>
                    <span class="badge bg-light text-dark border"><?= $l['jenis_kelamin'] == 'L' ? 'Laki-laki' : 'Perempuan' ?></span>
                </div>
                <small class="text-secondary"><i class="bi bi-geo-alt"></i> Dusun <?= $l['dusun'] ?>, RT <?= $l['rt'] ?>/RW <?= $l['rw'] ?></small>
            </div>
            <a href="lansia_tambah_periksa.php?id=<?= $id ?>" class="btn btn-periksa shadow-sm">
                <i class="bi bi-plus-circle me-1"></i> Periksa
            </a>
        </div>
    </div>

    <div class="card card-custom p-3">
        <h6 class="fw-bold mb-3 small"><i class="bi bi-graph-up text-primary me-2"></i>Grafik Tekanan Darah</h6>
        <canvas id="chartTensi" style="width: 100%; height: 200px;"></canvas>
    </div>

    <div class="card card-custom">
        <div class="card-header bg-white border-0 pt-3 d-flex justify-content-between">
            <h6 class="fw-bold mb-0 small"><i class="bi bi-clock-history text-success me-2"></i>Riwayat Pemeriksaan</h6>
            <small class="text-muted">Geser <i class="bi bi-arrow-right"></i></small>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0 text-center">
                    <thead>
                        <tr>
                            <th>Tgl</th>
                            <th>BB/TB</th>
                            <th>L.Perut</th>
                            <th>IMT</th>
                            <th>Tensi</th>
                            <th>GDS</th>
                            <th>AU</th>
                            <th>Kol</th>
                            <th>Fungsional</th>
                            <th>Mental</th>
                            <th>Obat/Catatan</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach (array_reverse($riwayat) as $r): ?>
                        <tr>
                            <td class="fw-bold"><?= date('d/m/y', strtotime($r['tgl_periksa'])) ?></td>
                            <td><?= $r['bb'] ?>/<?= $r['tb'] ?></td>
                            <td><?= $r['lingkar_perut'] ?></td>
                            <td <?= cekStatus($r['imt'], 'imt') ?>><?= $r['imt'] ?></td>
                            <td><span <?= cekTensi($r['tensi']) ?>><?= $r['tensi'] ?></span></td>
                            <td <?= cekStatus($r['gula_darah'], 'gds') ?>><?= $r['gula_darah'] ?></td>
                            <td <?= cekStatus($r['asam_urat'], 'asam_urat', $l['jenis_kelamin']) ?>><?= $r['asam_urat'] ?></td>
                            <td <?= cekStatus($r['kolesterol'], 'kolesterol') ?>><?= $r['kolesterol'] ?></td>
                            <td><?= $r['kemandirian'] ?></td>
                            <td><?= $r['skrining_mental'] ?></td>
                            <td class="text-start"><small><?= $r['catatan_obat'] ?: '-' ?></small></td>
                            <td>
                                <div class="d-flex gap-1 justify-content-center">
                                    <a href="lansia_periksa_edit.php?id=<?= $r['id_periksa_lansia'] ?>" class="btn btn-warning btn-action text-white">
                                        <i class="bi bi-pencil"></i>
                                    </a>
                                    <a href="lansia_periksa_hapus.php?id=<?= $r['id_periksa_lansia'] ?>&id_lansia=<?= $id ?>" 
                                       class="btn btn-danger btn-action" 
                                       onclick="return confirm('Hapus data pemeriksaan ini?')">
                                        <i class="bi bi-trash"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if(empty($riwayat)): ?>
                        <tr><td colspan="12" class="py-4 text-muted">Belum ada riwayat periksa</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script>
const ctx = document.getElementById('chartTensi').getContext('2d');
new Chart(ctx, {
    type: 'line',
    data: {
        labels: <?= json_encode($labels) ?>,
        datasets: [
            {
                label: 'Sistolik',
                data: <?= json_encode($systolic) ?>,
                borderColor: '#dc3545',
                backgroundColor: 'rgba(220, 53, 69, 0.1)',
                fill: true, tension: 0.3
            },
            {
                label: 'Diastolik',
                data: <?= json_encode($diastolic) ?>,
                borderColor: '#0d6efd',
                backgroundColor: 'rgba(13, 110, 253, 0.1)',
                fill: true, tension: 0.3
            }
        ]
    },
    options: {
        responsive: true,
        plugins: { legend: { position: 'bottom', labels: { boxWidth: 10, font: { size: 10 } } } },
        scales: { y: { grid: { display: false } }, x: { grid: { display: false } } }
    }
});
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>