<?php
include 'session_check.php';
include 'config/db.php';

$id = intval($_GET['id']);
$query = mysqli_query($conn, "SELECT * FROM pasien WHERE id = $id");
$data = mysqli_fetch_assoc($query);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $nik = $_POST['nik'];
    $nama = $_POST['nama'];
    $uploadPath = $data['hasil_lab']; // default path lama

    // Jika ada file baru diupload, simpan dan ganti file lama
    if (isset($_FILES['hasil_lab']) && $_FILES['hasil_lab']['error'] === 0) {
        $uploadDir = 'uploads/';
        if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
        $uploadPath = $uploadDir . basename($_FILES['hasil_lab']['name']);
        move_uploaded_file($_FILES['hasil_lab']['tmp_name'], $uploadPath);
    }

    $stmt = $conn->prepare("UPDATE pasien SET nik=?, nama=?, hasil_lab=? WHERE id=?");
    $stmt->bind_param("sssi", $nik, $nama, $uploadPath, $id);
    $stmt->execute();

    header("Location: index.php");
    exit;
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Edit Pasien</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
</head>
<body class="bg-light">
<div class="container mt-4">
    <h3>Edit Data Pasien</h3>
    <form method="POST" enctype="multipart/form-data">
        <div class="mb-2">
            <label>NIK</label>
            <input type="text" name="nik" class="form-control" value="<?= $data['nik'] ?>" required>
        </div>
        <div class="mb-2">
            <label>Nama</label>
            <input type="text" name="nama" class="form-control" value="<?= $data['nama'] ?>" required>
        </div>
        <div class="mb-2">
            <label>Hasil Lab (upload baru untuk mengganti)</label><br>
            <?php if (!empty($data['hasil_lab'])): ?>
                <a href="<?= $data['hasil_lab'] ?>" target="_blank">Lihat File Lama</a><br>
            <?php endif; ?>
            <input type="file" name="hasil_lab" class="form-control mt-1">
        </div>
        <button class="btn btn-success">Simpan Perubahan</button>
        <a href="index.php" class="btn btn-secondary">Batal</a>
    </form>
</div>
</body>
</html>
