<?php
// Filename: booking/admin/edit_booking.php
include '../../config.php';

// --- SECURITY CHECK ---
requireLogin();
$user_roles = explode(',', $_SESSION['role'] ?? '');
if (empty(array_intersect($user_roles, ['admin', 'admin_booking']))) {
    die("Access Denied.");
}

// Get Booking ID
$id = $_GET['id'] ?? 0;
if (!$id) { header("Location: manage.php"); exit; }

// Fetch Booking Data
$stmt = $pdo->prepare("SELECT * FROM bookings WHERE id = ?");
$stmt->execute([$id]);
$booking = $stmt->fetch();
if (!$booking) { die("Booking not found."); }

// Fetch Rooms for Dropdown
$rooms = $pdo->query("SELECT * FROM rooms ORDER BY name ASC")->fetchAll();

// Handle Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $room_id = $_POST['room_id'];
    $teacher_name = $_POST['teacher_name'];
    $booking_date = $_POST['booking_date'];
    $start_time = $_POST['start_time'];
    $end_time = $_POST['end_time'];
    $purpose = $_POST['purpose'];
    $status = $_POST['status'];

    // Basic Validation: Ensure end time is after start time
    if ($end_time <= $start_time) {
        $error = "End time must be after start time.";
    } else {
        // Check for conflicts (excluding current booking)
        $check = $pdo->prepare("SELECT COUNT(*) FROM bookings 
            WHERE room_id = ? AND booking_date = ? AND status = 'approved' AND id != ?
            AND ((start_time < ? AND end_time > ?) OR (start_time < ? AND end_time > ?))");
        $check->execute([$room_id, $booking_date, $id, $end_time, $start_time, $start_time, $end_time]);
        
        if ($status == 'approved' && $check->fetchColumn() > 0) {
            $error = "Room is already occupied during this time!";
        } else {
            // Update
            $update = $pdo->prepare("UPDATE bookings SET room_id=?, teacher_name=?, booking_date=?, start_time=?, end_time=?, purpose=?, status=? WHERE id=?");
            $update->execute([$room_id, $teacher_name, $booking_date, $start_time, $end_time, $purpose, $status, $id]);
            header("Location: manage.php?msg=updated");
            exit;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Booking</title>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <style>
        :root { --primary-grad: <?= getHeaderTheme() ?>; --bg-color: #f8f9fd; }
        body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: var(--bg-color); }
        .app-header { background: var(--primary-grad); padding: 20px 20px 40px 20px; border-radius: 0 0 35px 35px; color: white; margin-bottom: -20px;}
        .card-custom { border: none; border-radius: 20px; box-shadow: 0 5px 20px rgba(0,0,0,0.05); padding: 20px; background: white; }
    </style>
</head>
<body>

<div class="app-header">
    <div class="d-flex align-items-center mb-3">
        <a href="manage.php" class="text-white me-3"><i class="bi bi-arrow-left fs-4"></i></a>
        <h5 class="mb-0 fw-bold">Edit Booking</h5>
    </div>
</div>

<div class="container px-3">
    <div class="card-custom">
        <?php if(isset($error)): ?>
            <div class="alert alert-danger"><?= $error ?></div>
        <?php endif; ?>

        <form method="POST">
            <div class="mb-3">
                <label class="form-label small fw-bold text-muted">Teacher / Staff Name</label>
                <input type="text" name="teacher_name" class="form-control" value="<?= htmlspecialchars($booking['teacher_name']) ?>" required>
            </div>

            <div class="mb-3">
                <label class="form-label small fw-bold text-muted">Room / Facility</label>
                <select name="room_id" class="form-select">
                    <?php foreach($rooms as $r): ?>
                        <option value="<?= $r['id'] ?>" <?= $booking['room_id'] == $r['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($r['name']) ?> (<?= htmlspecialchars($r['location']) ?>)
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="row g-2 mb-3">
                <div class="col-12">
                    <label class="form-label small fw-bold text-muted">Date</label>
                    <input type="date" name="booking_date" class="form-control" value="<?= $booking['booking_date'] ?>" required>
                </div>
                <div class="col-6">
                    <label class="form-label small fw-bold text-muted">Start</label>
                    <input type="time" name="start_time" class="form-control" value="<?= $booking['start_time'] ?>" required>
                </div>
                <div class="col-6">
                    <label class="form-label small fw-bold text-muted">End</label>
                    <input type="time" name="end_time" class="form-control" value="<?= $booking['end_time'] ?>" required>
                </div>
            </div>

            <div class="mb-3">
                <label class="form-label small fw-bold text-muted">Purpose</label>
                <input type="text" name="purpose" class="form-control" value="<?= htmlspecialchars($booking['purpose']) ?>">
            </div>

            <div class="mb-4">
                <label class="form-label small fw-bold text-muted">Status</label>
                <select name="status" class="form-select fw-bold <?= $booking['status']=='approved'?'text-success':($booking['status']=='rejected'?'text-danger':'text-warning') ?>">
                    <option value="pending" class="text-warning" <?= $booking['status']=='pending'?'selected':'' ?>>Pending</option>
                    <option value="approved" class="text-success" <?= $booking['status']=='approved'?'selected':'' ?>>Approved</option>
                    <option value="rejected" class="text-danger" <?= $booking['status']=='rejected'?'selected':'' ?>>Rejected</option>
                </select>
            </div>

            <button type="submit" class="btn btn-primary w-100 py-2 fw-bold rounded-pill">Update Booking</button>
        </form>
    </div>
</div>
<?php include '../../menu.php'; ?>
</body>
</html>