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

$search = isset($_GET['search']) ? $_GET['search'] : '';
$query = "SELECT * FROM pasien WHERE nama LIKE '%$search%' OR nik LIKE '%$search%' ORDER BY id DESC";
$result = mysqli_query($conn, $query);
?>
<!DOCTYPE html>
<html>
<head>
    <title>Data Pasien HPV DNA</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 class="mb-3">Data Pasien HPV DNA</h3>
    <form method="get" class="mb-3">
        <input type="text" name="search" class="form-control" placeholder="Cari Nama atau NIK..." value="<?= htmlspecialchars($search) ?>">
    </form>
    <?php if ($_SESSION['role'] === 'admin'): ?>
    <a href="tambah.php" class="btn btn-primary mb-2">+ Tambah Pasien</a>
    <?php endif; ?>

    <?php if ($_SESSION['role'] === 'admin'): ?>
        <a href="auth/register.php" class="btn btn-secondary mb-2">+ Tambah Petugas</a>
    <?php endif; ?>
    <a href="auth/logout.php" class="btn btn-danger mb-2 float-end">Logout</a>
    <table class="table table-bordered table-striped">
        <thead class="table-dark text-center">
            <tr>
                <th>NIK</th>
                <th>Nama</th>
                <th>Hasil Lab</th>
                <th>Aksi</th>
            </tr>
        </thead>
        <tbody>
        <?php while ($row = mysqli_fetch_assoc($result)): ?>
            <tr>
                <td><?= $row['nik'] ?></td>
                <td><?= $row['nama'] ?></td>
                <td>
                    <?php if ($row['hasil_lab']): ?>
                        <a href="<?= $row['hasil_lab'] ?>" target="_blank" class="btn btn-sm btn-info mb-1">Preview</a><br>
                        <a href="<?= $row['hasil_lab'] ?>" download class="btn btn-sm btn-secondary">Download</a>
                    <?php else: ?>
                        <em>Belum</em>
                    <?php endif; ?>
                </td>
                <td>
                    <a href='view.php?id=<?= $row['id'] ?>' class='btn btn-info btn-sm'>Lihat</a>
                    <?php if ($_SESSION['role'] === 'admin'): ?>
                        <a href='edit.php?id=<?= $row['id'] ?>' class='btn btn-warning btn-sm'>Edit</a>
                        <a href='hapus.php?id=<?= $row['id'] ?>' class='btn btn-danger btn-sm' onclick="return confirm('Yakin ingin hapus?')">Hapus</a>
                    <?php endif; ?>
                </td>
            </tr>
        <?php endwhile; ?>
        </tbody>
    </table>
</div>
</body>
</html>
