<?php
session_start();

require 'db.php';
require_once 'includes/send_email.php';

if (!isset($_SESSION['student_id'])) {
    header("Location: student-login.php");  // Updated login path
    exit();
}

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

// Booking submission
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $slot_id = $_POST['slot_id'] ?? '';

    if ($slot_id) {
        $stmt = $conn->prepare("SELECT id FROM BookedDrives WHERE slot_id = ?");
        $stmt->bind_param("i", $slot_id);
        $stmt->execute();
        $stmt->store_result();

        if ($stmt->num_rows > 0) {
            $error = "This slot has already been booked.";
        } else {
            $stmt->close();
            $stmt = $conn->prepare("INSERT INTO BookedDrives (student_id, slot_id) VALUES (?, ?)");
            $stmt->bind_param("ii", $student_id, $slot_id);
            if ($stmt->execute()) {
                $success = "Drive booked successfully.";

                // Fetch student email for notification
                $stmt_student = $conn->prepare("SELECT email, first_name FROM Students WHERE id = ?");
                $stmt_student->bind_param("i", $student_id);
                $stmt_student->execute();
                $result_student = $stmt_student->get_result();
                $student = $result_student->fetch_assoc();

                if ($student) {
                    // Fetch drive details
                    $stmt_slot = $conn->prepare("
                        SELECT ia.available_date, ia.start_time, ia.end_time, i.first_name, i.last_name
                        FROM InstructorAvailability ia
                        JOIN Instructors i ON ia.instructor_id = i.id
                        WHERE ia.id = ?
                    ");
                    $stmt_slot->bind_param("i", $slot_id);
                    $stmt_slot->execute();
                    $result_slot = $stmt_slot->get_result();
                    $slot = $result_slot->fetch_assoc();

                    if ($slot) {
                        $subject = "Drive Time Booking Confirmation";
                        $body_html = "
                            <p>Hello {$student['first_name']},</p>
                            <p>Your drive time has been successfully booked:</p>
                            <ul>
                                <li><strong>Date:</strong> {$slot['available_date']}</li>
                                <li><strong>Time:</strong> {$slot['start_time']} - {$slot['end_time']}</li>
                                <li><strong>Instructor:</strong> {$slot['first_name']} {$slot['last_name']}</li>
                            </ul>
                            <p>If you have questions or need to reschedule, please visit your student dashboard.</p>
                            <hr>
                            <p style='font-size:0.9em;color:#888;'>This email is not monitored. Please forward all requests to <a href='mailto:info@tandddrivingacademy.com'>info@tandddrivingacademy.com</a>.</p>
                        ";

                        send_email($student['email'], $student['first_name'], $subject, $body_html);
                    }

                    $stmt_slot->close();
                }

                $stmt_student->close();
            } else {
                $error = "Error booking the drive.";
            }
        }
        $stmt->close();
    } else {
        $error = "Please select a time slot.";
    }
}

// Fetch available slots (only unbooked)
$available_slots = $conn->query("
    SELECT ia.id, ia.available_date, ia.start_time, ia.end_time, i.first_name, i.last_name
    FROM InstructorAvailability ia
    JOIN Instructors i ON ia.instructor_id = i.id
    WHERE ia.id NOT IN (SELECT slot_id FROM BookedDrives)
    ORDER BY ia.available_date, ia.start_time
");
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Book a Drive</title>
    <style>
        body { font-family: Arial, sans-serif; background: #f4f4f4; margin: 40px; }
        .container { max-width: 600px; margin: auto; background: white; padding: 25px; border-radius: 10px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
        h2 { text-align: center; }
        label, select, input[type=submit], .dashboard-btn { display: block; width: 100%; margin-top: 10px; }
        input[type=submit], .dashboard-btn { background: #007bff; color: white; border: none; padding: 10px; cursor: pointer; border-radius: 4px; }
        .success { color: green; text-align: center; }
        .error { color: red; text-align: center; }
    </style>
</head>
<body>
<div class="container">
    <h2>Book Your Drive Time</h2>

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

    <form method="post">
        <label for="slot_id">Choose a Time Slot:</label>
        <select name="slot_id" required>
            <option value="">-- Select Slot --</option>
            <?php while ($slot = $available_slots->fetch_assoc()): ?>
                <option value="<?= $slot['id'] ?>">
                    <?= htmlspecialchars($slot['available_date']) ?> |
                    <?= $slot['start_time'] ?> - <?= $slot['end_time'] ?> with
                    <?= htmlspecialchars($slot['first_name'] . ' ' . $slot['last_name']) ?>
                </option>
            <?php endwhile; ?>
        </select>

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

    <form method="get" action="student-dashboard.php">
        <button type="submit" class="dashboard-btn">Return to Dashboard</button>
    </form>
</div>
</body>
</html>




