<?php
include '../includes/db.php';

// Handle deletion
if(isset($_GET['delete'])){
    $id = (int)$_GET['delete'];
    $conn->query("DELETE FROM appointments WHERE id=$id");
    header("Location: ".$_SERVER['PHP_SELF']);
    exit;
}

$result = $conn->query("SELECT * FROM appointments ORDER BY created_at DESC");
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Appointments | Admin</title>
<style>
table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 20px;
}
th, td {
    padding: 10px;
    border: 1px solid #ddd;
    text-align: center;
}
th {
    background: #25A9C2;
    color: white;
}
.status-pending { color: orange; font-weight: bold; }
.status-approved { color: green; font-weight: bold; }
.status-cancelled { color: red; font-weight: bold; }

.btn {
    padding: 6px 12px;
    border-radius: 5px;
    border: none;
    cursor: pointer;
    font-weight: bold;
    text-decoration: none;
}
.btn-approve { background: #28a745; color: #fff; }
.btn-cancel { background: #dc3545; color: #fff; }
.btn-delete { background: #6c757d; color: #fff; }
.btn-disabled {
    background: #ccc;
    cursor: not-allowed;
}
</style>
</head>
<?php include 'header.php'; ?>
<body>

<h2>Appointment Requests</h2>

<table>
<tr>
    <th>#</th>
    <th>Name</th>
    <th>Phone</th>
    <th>Department</th>
    <th>Date</th>
    <th>Time</th>
    <th>Status</th>
    <th>Action</th>
</tr>

<?php while($row = $result->fetch_assoc()): ?>
<tr>
    <td><?= $row['id'] ?></td>
    <td><?= htmlspecialchars($row['full_name']) ?></td>
    <td><?= htmlspecialchars($row['phone']) ?></td>
    <td><?= htmlspecialchars($row['department']) ?></td>
    <td><?= $row['appointment_date'] ?></td>
    <td><?= $row['appointment_time'] ?></td>

    <td class="status-<?= strtolower($row['status']) ?>">
        <?= $row['status'] ?>
    </td>

    <td>
        <?php if ($row['status'] === 'Pending'): ?>
            <a href="update_appointment.php?id=<?= $row['id'] ?>&status=Approved"
               class="btn btn-approve"
               onclick="return confirm('Approve this appointment?')">
               Approve
            </a>

            <a href="update_appointment.php?id=<?= $row['id'] ?>&status=Cancelled"
               class="btn btn-cancel"
               onclick="return confirm('Cancel this appointment?')">
               Cancel
            </a>
        <?php else: ?>
            <span class="btn btn-disabled">No Action</span>
        <?php endif; ?>

        <!-- Delete button -->
        <a href="?delete=<?= $row['id'] ?>" class="btn btn-delete"
           onclick="return confirm('Are you sure you want to delete this appointment?')">
           Delete
        </a>
    </td>
</tr>
<?php endwhile; ?>

</table>

</body>
</html>
