<?php
session_start();
require 'db.php';
require_once 'includes/send_email.php';

if (!isset($_SESSION['instructor_id'])) {
    header("Location: instructor-login.php");
    exit();
}

$instructor_id = $_SESSION['instructor_id'];
$success = "";
$error = "";
$current_date = date("Y-m-d");

// Handle drive booking
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['student_id'], $_POST['slot_id'])) {
    $student_id = $_POST['student_id'];
    $slot_id = $_POST['slot_id'];

    // Duration check
    $check_slot = $conn->prepare("SELECT start_time, end_time FROM InstructorAvailability WHERE id = ?");
    $check_slot->bind_param("i", $slot_id);
    $check_slot->execute();
    $result_slot = $check_slot->get_result();
    $slot_info = $result_slot->fetch_assoc();
    $check_slot->close();

    if ($slot_info) {
        $start = new DateTime($slot_info['start_time']);
        $end = new DateTime($slot_info['end_time']);
        $interval = $start->diff($end);
        $duration_in_hours = $interval->h + ($interval->i / 60);

        if ($duration_in_hours <= 0 || $duration_in_hours > 2) {
            $error = "Drive time must be 1 or 2 hours only.";
        } else {
            $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.";
            } else {
                $error = "Error booking the drive.";
            }
            $stmt->close();
        }
    } else {
        $error = "Selected slot does not exist.";
    }
}

// Handle drive cancellation
if (isset($_POST['cancel_drive_id'])) {
    $cancel_id = $_POST['cancel_drive_id'];
    $stmt_cancel = $conn->prepare("DELETE FROM BookedDrives WHERE id = ?");
    $stmt_cancel->bind_param("i", $cancel_id);
    if ($stmt_cancel->execute()) {
        $success = "Drive booking canceled.";
    } else {
        $error = "Error canceling drive.";
    }
    $stmt_cancel->close();
}

// Handle drive modification
if (isset($_POST['modify_drive_id'], $_POST['new_slot_id'])) {
    $modify_id = $_POST['modify_drive_id'];
    $new_slot_id = $_POST['new_slot_id'];

    $stmt_details = $conn->prepare("SELECT student_id FROM BookedDrives WHERE id = ?");
    $stmt_details->bind_param("i", $modify_id);
    $stmt_details->execute();
    $result = $stmt_details->get_result();
    $booking = $result->fetch_assoc();
    $student_id = $booking['student_id'];
    $stmt_details->close();

    // Duration check on new slot
    $check_slot = $conn->prepare("SELECT start_time, end_time FROM InstructorAvailability WHERE id = ?");
    $check_slot->bind_param("i", $new_slot_id);
    $check_slot->execute();
    $result_slot = $check_slot->get_result();
    $slot_info = $result_slot->fetch_assoc();
    $check_slot->close();

    $start = new DateTime($slot_info['start_time']);
    $end = new DateTime($slot_info['end_time']);
    $interval = $start->diff($end);
    $duration_in_hours = $interval->h + ($interval->i / 60);

    if ($duration_in_hours <= 0 || $duration_in_hours > 2) {
        $error = "Drive time must be 1 or 2 hours only.";
    } else {
        $stmt_update = $conn->prepare("UPDATE BookedDrives SET slot_id = ? WHERE id = ?");
        $stmt_update->bind_param("ii", $new_slot_id, $modify_id);
        if ($stmt_update->execute()) {
            $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();
            $stmt_student->close();

            $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", $new_slot_id);
            $stmt_slot->execute();
            $result_slot = $stmt_slot->get_result();
            $slot = $result_slot->fetch_assoc();
            $stmt_slot->close();

            if ($student && $slot) {
                $subject = "Drive Time Rescheduled by Instructor";
                $body_html = "<p>Hello {$student['first_name']},</p>
                    <p>Your drive time has been rescheduled:</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 any questions, please contact our office or check 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);
            }

            $success = "Drive updated and student notified.";
        } else {
            $error = "Error updating drive.";
        }
        $stmt_update->close();
    }
}

$students = $conn->query("SELECT id, first_name, last_name FROM Students ORDER BY last_name, first_name");
$slots = $conn->prepare("SELECT ia.id, ia.available_date, ia.start_time, ia.end_time FROM InstructorAvailability ia WHERE ia.instructor_id = ? AND ia.id NOT IN (SELECT slot_id FROM BookedDrives) ORDER BY ia.available_date, ia.start_time");
$slots->bind_param("i", $instructor_id);
$slots->execute();
$available_slots = $slots->get_result();

$booked = $conn->prepare("SELECT bd.id, bd.slot_id, s.first_name, s.last_name, ia.available_date, ia.start_time, ia.end_time FROM BookedDrives bd JOIN Students s ON bd.student_id = s.id JOIN InstructorAvailability ia ON bd.slot_id = ia.id WHERE ia.instructor_id = ? AND ia.available_date >= ? ORDER BY ia.available_date, ia.start_time");
$booked->bind_param("is", $instructor_id, $current_date);
$booked->execute();
$booked_drives = $booked->get_result();
$available_slots->data_seek(0);
$all_slots = $available_slots->fetch_all(MYSQLI_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Instructor Drive Booking</title>
  <style>
    body { font-family: Arial, sans-serif; margin: 40px; background-color: #f5f5f5; }
    .container { max-width: 700px; margin: auto; background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
    h2, h3 { text-align: center; margin-bottom: 20px; }
    label { display: block; margin-top: 10px; }
    select, input[type=submit], button { width: 100%; padding: 10px; margin-top: 5px; border-radius: 5px; border: 1px solid #ccc; }
    .success { color: green; text-align: center; margin-bottom: 20px; }
    .error { color: red; text-align: center; margin-bottom: 20px; }
    table { width: 100%; border-collapse: collapse; margin-top: 30px; }
    th, td { border: 1px solid #ccc; padding: 8px; text-align: left; }
    th { background-color: #f0f0f0; }
    form.inline { display: inline; }
    button.cancel-btn { background: #dc3545; color: white; border: none; cursor: pointer; padding: 6px 10px; border-radius: 4px; }
  </style>
</head>
<body>
<div class="container">
  <h2>Book a 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="student_id">Select Student:</label>
    <select name="student_id" required>
      <option value="">-- Select Student --</option>
      <?php while ($student = $students->fetch_assoc()): ?>
        <option value="<?= $student['id'] ?>">
          <?= htmlspecialchars($student['last_name'] . ", " . $student['first_name']) ?>
        </option>
      <?php endwhile; ?>
    </select>

    <label for="slot_id">Select Available Time Slot:</label>
    <select name="slot_id" required>
      <option value="">-- Select Time Slot --</option>
      <?php foreach ($all_slots as $slot): ?>
        <option value="<?= $slot['id'] ?>">
          <?= htmlspecialchars($slot['available_date']) ?> | <?= $slot['start_time'] ?> - <?= $slot['end_time'] ?>
        </option>
      <?php endforeach; ?>
    </select>

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

  <h3>Your Upcoming Drives</h3>
  <table>
    <thead>
      <tr>
        <th>Student</th>
        <th>Date</th>
        <th>Time</th>
        <th>Action</th>
      </tr>
    </thead>
    <tbody>
      <?php $booked_drives->data_seek(0); while ($drive = $booked_drives->fetch_assoc()): ?>
      <tr>
        <td><?= htmlspecialchars($drive['last_name'] . ", " . $drive['first_name']) ?></td>
        <td><?= $drive['available_date'] ?></td>
        <td><?= $drive['start_time'] ?> - <?= $drive['end_time'] ?></td>
        <td>
          <form method="post" class="inline">
            <input type="hidden" name="cancel_drive_id" value="<?= $drive['id'] ?>">
            <button type="submit" class="cancel-btn">Cancel</button>
          </form>
          <button onclick="openModal(<?= $drive['id'] ?>)">Modify</button>
        </td>
      </tr>
      <?php endwhile; ?>
    </tbody>
  </table>

  <?php $booked_drives->data_seek(0); while ($drive = $booked_drives->fetch_assoc()): ?>
  <div id="modal-<?= $drive['id'] ?>" style="display:none; position:fixed; top:10%; left:50%; transform:translateX(-50%); background:#fff; padding:20px; border:1px solid #ccc; border-radius:8px; z-index:1000; box-shadow:0 0 10px rgba(0,0,0,0.2);">
    <form method="post">
      <h3>Reschedule for <?= htmlspecialchars($drive['last_name'] . ', ' . $drive['first_name']) ?></h3>
      <input type="hidden" name="modify_drive_id" value="<?= $drive['id'] ?>">
      <label>Select New Slot:</label>
      <select name="new_slot_id" required>
        <option value="">-- Select New Slot --</option>
        <?php foreach ($all_slots as $slot): ?>
        <option value="<?= $slot['id'] ?>">
          <?= htmlspecialchars($slot['available_date']) ?> | <?= $slot['start_time'] ?> - <?= $slot['end_time'] ?>
        </option>
        <?php endforeach; ?>
      </select>
      <br><br>
      <button type="submit">Confirm Change</button>
      <button type="button" onclick="closeModal(<?= $drive['id'] ?>)">Cancel</button>
    </form>
  </div>
  <?php endwhile; ?>
</div>

<script>
function openModal(id) {
  document.getElementById('modal-' + id).style.display = 'block';
}
function closeModal(id) {
  document.getElementById('modal-' + id).style.display = 'none';
}
</script>
</body>
</html>
