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

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

$success = "";
$error = "";
$current_date = date("Y-m-d");

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['drive_id'], $_POST['new_instructor_id'])) {
    $drive_id = $_POST['drive_id'];
    $new_instructor_id = $_POST['new_instructor_id'];

    $stmt = $conn->prepare("SELECT bd.student_id, ia.available_date, ia.start_time, ia.end_time FROM BookedDrives bd JOIN InstructorAvailability ia ON bd.slot_id = ia.id WHERE bd.id = ?");
    $stmt->bind_param("i", $drive_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $drive = $result->fetch_assoc();
    $stmt->close();

    if ($drive) {
        $stmt_slot = $conn->prepare("SELECT id FROM InstructorAvailability WHERE instructor_id = ? AND available_date = ? AND start_time = ? AND end_time = ?");
        $stmt_slot->bind_param("isss", $new_instructor_id, $drive['available_date'], $drive['start_time'], $drive['end_time']);
        $stmt_slot->execute();
        $result_slot = $stmt_slot->get_result();

        if ($slot = $result_slot->fetch_assoc()) {
            $new_slot_id = $slot['id'];
        } else {
            $stmt_insert = $conn->prepare("INSERT INTO InstructorAvailability (instructor_id, available_date, start_time, end_time) VALUES (?, ?, ?, ?)");
            $stmt_insert->bind_param("isss", $new_instructor_id, $drive['available_date'], $drive['start_time'], $drive['end_time']);
            $stmt_insert->execute();
            $new_slot_id = $stmt_insert->insert_id;
            $stmt_insert->close();
        }
        $stmt_slot->close();

        $stmt_update = $conn->prepare("UPDATE BookedDrives SET slot_id = ? WHERE id = ?");
        $stmt_update->bind_param("ii", $new_slot_id, $drive_id);
        if ($stmt_update->execute()) {
            $stmt_student = $conn->prepare("SELECT email, first_name FROM Students WHERE id = ?");
            $stmt_student->bind_param("i", $drive['student_id']);
            $stmt_student->execute();
            $student = $stmt_student->get_result()->fetch_assoc();
            $stmt_student->close();

            $stmt_instructor = $conn->prepare("SELECT first_name, last_name FROM Instructors WHERE id = ?");
            $stmt_instructor->bind_param("i", $new_instructor_id);
            $stmt_instructor->execute();
            $instructor = $stmt_instructor->get_result()->fetch_assoc();
            $stmt_instructor->close();

            $subject = "Drive Time Instructor Reassignment";
            $body_html = "<p>Hello {$student['first_name']},</p>
                <p>Your upcoming drive time has been reassigned to a new instructor:</p>
                <ul>
                    <li><strong>Date:</strong> {$drive['available_date']}</li>
                    <li><strong>Time:</strong> {$drive['start_time']} - {$drive['end_time']}</li>
                    <li><strong>New Instructor:</strong> {$instructor['first_name']} {$instructor['last_name']}</li>
                </ul>
                <p>If you have any questions, please contact our office.</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 = "Instructor reassigned and student notified.";
        } else {
            $error = "Error updating booking.";
        }
        $stmt_update->close();
    }
}

$drives = $conn->query("SELECT bd.id as drive_id, s.first_name AS student_first, s.last_name AS student_last, ia.available_date, ia.start_time, ia.end_time, i.first_name AS inst_first, i.last_name AS inst_last FROM BookedDrives bd JOIN Students s ON bd.student_id = s.id JOIN InstructorAvailability ia ON bd.slot_id = ia.id JOIN Instructors i ON ia.instructor_id = i.id WHERE ia.available_date >= '$current_date' ORDER BY ia.available_date, ia.start_time");
$instructors = $conn->query("SELECT id, first_name, last_name FROM Instructors ORDER BY last_name, first_name");
$instructor_options = $instructors->fetch_all(MYSQLI_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Admin: Reassign Drives</title>
  <style>
    body { font-family: Arial, sans-serif; padding: 20px; background: #f9f9f9; }
    table { width: 100%; border-collapse: collapse; margin-top: 20px; }
    th, td { padding: 10px; border: 1px solid #ccc; text-align: left; }
    th { background: #eee; }
    form.inline { display: inline; }
    select, button { padding: 6px; border-radius: 4px; }
    .success { color: green; }
    .error { color: red; }
    .nav-btn { margin-top: 20px; padding: 10px 20px; background: #007bff; color: white; border: none; border-radius: 5px; cursor: pointer; text-decoration: none; }
  </style>
</head>
<body>
  <h2>Admin: Reassign Instructors for Booked Drives</h2>
  <?php if ($success): ?><p class="success"><?= $success ?></p><?php endif; ?>
  <?php if ($error): ?><p class="error"><?= $error ?></p><?php endif; ?>

  <table>
    <thead>
      <tr>
        <th>Student</th>
        <th>Date</th>
        <th>Time</th>
        <th>Current Instructor</th>
        <th>New Instructor</th>
        <th>Action</th>
      </tr>
    </thead>
    <tbody>
      <?php while ($drive = $drives->fetch_assoc()): ?>
      <tr>
        <td><?= htmlspecialchars($drive['student_last'] . ", " . $drive['student_first']) ?></td>
        <td><?= $drive['available_date'] ?></td>
        <td><?= $drive['start_time'] ?> - <?= $drive['end_time'] ?></td>
        <td><?= htmlspecialchars($drive['inst_first'] . " " . $drive['inst_last']) ?></td>
        <td>
          <form method="post" class="inline">
            <input type="hidden" name="drive_id" value="<?= $drive['drive_id'] ?>">
            <select name="new_instructor_id" required>
              <option value="">-- Select --</option>
              <?php foreach ($instructor_options as $inst): ?>
                <option value="<?= $inst['id'] ?>">
                  <?= htmlspecialchars($inst['last_name'] . ", " . $inst['first_name']) ?>
                </option>
              <?php endforeach; ?>
            </select>
        </td>
        <td>
            <button type="submit">Confirm</button>
          </form>
        </td>
      </tr>
      <?php endwhile; ?>
    </tbody>
  </table>

  <div style="text-align:center;">
    <a href="admin-dashboard.php" class="nav-btn">Done Reassigning</a>
  </div>
</body>
</html>
