<?php
session_start();
require 'db.php';

// Redirect if not logged in
if (!isset($_SESSION['student_id'])) {
    header("Location: login.php");
    exit();
}

$student_id = $_SESSION['student_id'];
$success = "";
$error = "";

// Handle booking submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $availability_id = $_POST['availability_id'] ?? '';

    if ($availability_id) {
        // Check if slot is already booked
        $stmt = $conn->prepare("SELECT id FROM BookedDrives WHERE availability_id = ?");
        $stmt->bind_param("i", $availability_id);
        $stmt->execute();
        $stmt->store_result();

        if ($stmt->num_rows > 0) {
            $error = "This slot has already been booked.";
        } else {
            $stmt = $conn->prepare("INSERT INTO BookedDrives (availability_id, student_id) VALUES (?, ?)");
            $stmt->bind_param("ii", $availability_id, $student_id);
            if ($stmt->execute()) {
                $success = "Drive successfully booked!";
            } else {
                $error = "Booking failed. Please try again.";
            }
        }
        $stmt->close();
    } else {
        $error = "No slot selected.";
    }
}

// Fetch all unbooked availability slots
$sql = "SELECT ia.id, i.name, ia.available_date, ia.start_time, ia.end_time
        FROM InstructorAvailability ia
        JOIN Instructors i ON ia.instructor_id = i.id
        LEFT JOIN BookedDrives bd ON ia.id = bd.availability_id
        WHERE bd.id IS NULL AND ia.available_date >= CURDATE()
        ORDER BY ia.available_date, ia.start_time";
$result = $conn->query($sql);
$slots = $result->fetch_all(MYSQLI_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Book Drive Time</title>
    <style>
        body { font-family: Arial; padding: 2em; background: #f7f7f7; }
        .container { background: #fff; padding: 20px; border-radius: 8px; max-width: 600px; margin: auto; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
        select, input[type="submit"] { width: 100%; padding: 10px; margin-top: 15px; border-radius: 4px; border: 1px solid #ccc; }
        .success { color: green; margin-top: 15px; }
        .error { color: red; margin-top: 15px; }
        .nav { margin-top: 20px; display: flex; justify-content: space-between; }
        .nav a { text-decoration: none; color: #007BFF; }
    </style>
</head>
<body>
    <div class="container">
        <h2>Book a Drive Slot</h2>

        <?php if ($success): ?>
            <p class="success"><?php echo $success; ?></p>
        <?php elseif ($error): ?>
            <p class="error"><?php echo $error; ?></p>
        <?php endif; ?>

        <form method="POST">
            <label for="availability_id">Available Drive Times:</label>
            <select name="availability_id" required>
                <option value="">Select a slot...</option>
                <?php foreach ($slots as $slot): ?>
                    <option value="<?php echo $slot['id']; ?>">
                        <?php echo $slot['available_date'] . ' | ' . date("g:i A", strtotime($slot['start_time'])) . '–' . date("g:i A", strtotime($slot['end_time'])) . ' with ' . $slot['name']; ?>
                    </option>
                <?php endforeach; ?>
            </select>

            <input type="submit" value="Book Drive">
        </form>

        <div class="nav">
            <a href="student-dashboard.php">Return to Dashboard</a>
            <a href="book-drive.php">Book Another</a>
        </div>
    </div>
</body>
</html>
