<?php
session_start();
if (!isset($_SESSION['admin_id'])) { header("Location: login.php"); exit(); }
include '../include/config.php';

// Handle status update
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    $patient_id = $_POST['patient_id'];
    $new_status = $_POST['status'];
    $conn->query("UPDATE patients SET status='$new_status' WHERE patient_id='$patient_id'");
    $msg = "Patient status updated.";
}

$patients = $conn->query("SELECT * FROM patients ORDER BY created_at DESC");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Patients - UHD</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css">
    <style>body{background:#0a3d2f;}.navbar{background:#064e3b;}.card{border-radius:20px;background:rgba(255,255,255,0.95);}</style>
</head>
<body>
<nav class="navbar navbar-dark"><div class="container"><span class="navbar-brand"><i class="fas fa-users"></i> Manage Patients</span><a href="dashboard.php" class="btn btn-light btn-sm">Back</a></div></nav>
<div class="container mt-4"><div class="card"><div class="card-header bg-success text-white">Patient List</div><div class="card-body">
<?php if(isset($msg)) echo "<div class='alert alert-success'>$msg</div>"; ?>
<div class="table-responsive"><table class="table table-hover"><thead><tr><th>ID</th><th>Name</th><th>Email</th><th>Phone</th><th>Status</th><th>Action</th></tr></thead><tbody>
<?php while($p=$patients->fetch_assoc()): ?>
<tr>
    <td><?= $p['patient_id'] ?></td>
    <td><?= htmlspecialchars($p['first_name'].' '.$p['last_name']) ?></td>
    <td><?= $p['email'] ?></td>
    <td><?= $p['phone'] ?></td>
    <td>
        <form method="POST" class="d-inline">
            <input type="hidden" name="patient_id" value="<?= $p['patient_id'] ?>">
            <select name="status" onchange="this.form.submit()" class="form-select form-select-sm" style="width:auto;display:inline-block;">
                <option value="active" <?= $p['status']=='active'?'selected':'' ?>>Active</option>
                <option value="pending" <?= $p['status']=='pending'?'selected':'' ?>>Pending</option>
                <option value="inactive" <?= $p['status']=='inactive'?'selected':'' ?>>Inactive</option>
            </select>
            <input type="hidden" name="action" value="update">
        </form>
    </td>
    <td><a href="view_patient.php?id=<?= $p['patient_id'] ?>" class="btn btn-sm btn-info">View</a></td>
</tr>
<?php endwhile; ?>
</tbody></table></div>
</div></div></div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>