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

// Update appointment status
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_status'])) {
    $appointment_id = (int)$_POST['appointment_id'];
    $new_status = $_POST['status'];
    $conn->query("UPDATE appointments SET status = '$new_status' WHERE id = $appointment_id");
    $msg = "Appointment updated!";
}

$appointments = $conn->query("SELECT a.*, p.first_name, p.last_name, p.phone FROM appointments a JOIN patients p ON a.patient_id = p.patient_id ORDER BY a.appointment_date DESC");
?>
<!DOCTYPE html>
<html><head><title>Manage Appointments</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"></head>
<body><div class="container mt-4"><h2>Appointments</h2><?php if(isset($msg)) echo "<div class='alert alert-success'>$msg</div>"; ?>
<div class="table-responsive"><table class="table table-bordered"><thead><tr><th>Patient</th><th>Date</th><th>Time</th><th>Reason</th><th>Status</th><th>Action</th></tr></thead><tbody>
<?php while($a = $appointments->fetch_assoc()): ?>
<tr><td><?= $a['first_name'].' '.$a['last_name'] ?></td><td><?= date('M d, Y', strtotime($a['appointment_date'])) ?></td><td><?= date('h:i A', strtotime($a['appointment_time'])) ?></td><td><?= htmlspecialchars(substr($a['reason'],0,50)) ?></td>
<td>
    <form method="POST" class="d-inline">
        <input type="hidden" name="appointment_id" value="<?= $a['id'] ?>">
        <select name="status" onchange="this.form.submit()" class="form-select form-select-sm" style="width:auto;display:inline-block;">
            <option value="pending" <?= $a['status']=='pending'?'selected':'' ?>>Pending</option>
            <option value="confirmed" <?= $a['status']=='confirmed'?'selected':'' ?>>Confirmed</option>
            <option value="completed" <?= $a['status']=='completed'?'selected':'' ?>>Completed</option>
            <option value="cancelled" <?= $a['status']=='cancelled'?'selected':'' ?>>Cancelled</option>
        </select>
        <input type="hidden" name="update_status" value="1">
    </form>
</td>
<td><a href="view_patient.php?id=<?= $a['patient_id'] ?>" class="btn btn-sm btn-info">View Patient</a></td></tr>
<?php endwhile; ?>
</tbody></table></div><a href="dashboard.php" class="btn btn-secondary">Back</a></div></body>
</html>