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

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

$instructor_id = $_SESSION['instructor_id'];
$instructor_name = $_SESSION['instructor_name'] ?? 'Instructor';
$success = '';
$error = '';

// Prevent resubmission on reload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['available_date'], $_POST['start_time'], $_POST['end_time'])) {
    $date = $_POST['available_date'];
    $start = $_POST['start_time'];
    $end = $_POST['end_time'];

    // Check for conflicts (assuming 3 cars max)
    $check = $conn->prepare("
        SELECT COUNT(*) AS total 
        FROM InstructorAvailability 
        WHERE available_date = ? 
        AND (
            (start_time <= ? AND end_time > ?) OR 
            (start_time < ? AND end_time >= ?) OR 
            (start_time >= ? AND end_time <= ?)
        )
    ");
    $check->bind_param("sssssss", $date, $start, $start, $end, $end, $start, $end);
    $check->execute();
    $result = $check->get_result()->fetch_assoc();
    $check->close();

    if ($result['total'] >= 3) {
        $error = "This time slot is already full (3 instructors scheduled). Please choose a different time.";
    } else {
        // Check for instructor's own overlap
        $self_check = $conn->prepare("
            SELECT id FROM InstructorAvailability 
            WHERE instructor_id = ? AND available_date = ? 
            AND (
                (start_time <= ? AND end_time > ?) OR 
                (start_time < ? AND end_time >= ?) OR 
                (start_time >= ? AND end_time <= ?)
            )
        ");
        $self_check->bind_param("isssssss", $instructor_id, $date, $start, $start, $end, $end, $start, $end);
        $self_check->execute();
        $self_conflict = $self_check->get_result()->fetch_assoc();
        $self_check->close();

        if ($self_conflict) {
            $error = "You already have availability during this time.";
        } else {
            $stmt = $conn->prepare("INSERT INTO InstructorAvailability (instructor_id, available_date, start_time, end_time) VALUES (?, ?, ?, ?)");
            $stmt->bind_param("isss", $instructor_id, $date, $start, $end);
            $stmt->execute();
            $stmt->close();
            header("Location: schedule-availability.php?success=1");
            exit();
        }
    }
}

if (isset($_GET['success'])) {
    $success = "Availability successfully added!";
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Schedule Availability</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background: #f4f6f8;
            margin: 0;
            padding: 20px;
        }
        .container {
            width: 500px;
            background: white;
            margin: 50px auto;
            padding: 25px;
            border-radius: 10px;
            box-shadow: 0px 0px 8px rgba(0,0,0,0.1);
        }
        h2 {
            margin-top: 0;
            text-align: center;
        }
        label {
            display: block;
            margin-top: 15px;
        }
        input[type="date"],
        input[type="time"],
        input[type="submit"],
        a.button {
            width: 100%;
            padding: 10px;
            margin-top: 8px;
            border: 1px solid #ccc;
            border-radius: 6px;
            box-sizing: border-box;
        }
        input[type="submit"] {
            background: #28a745;
            color: white;
            border: none;
            cursor: pointer;
        }
        .success {
            color: green;
            text-align: center;
        }
        .error {
            color: red;
            text-align: center;
        }
        .menu {
            text-align: right;
        }
        .menu a {
            text-decoration: none;
            margin-left: 10px;
            color: #007bff;
        }
        a.button {
            display: inline-block;
            background: #007bff;
            color: white;
            text-align: center;
            text-decoration: none;
        }
    </style>
</head>
<body>
    <div class="menu">
        <strong><?= htmlspecialchars($instructor_name) ?></strong>
        <a href="instructor-dashboard.php">Dashboard</a>
        <a href="logout.php">Logout</a>
    </div>

    <div class="container">
        <h2>Set Your Drive Availability</h2>
        <?php if ($success): ?><p class="success"><?= $success ?></p><?php endif; ?>
        <?php if ($error): ?><p class="error"><?= $error ?></p><?php endif; ?>

        <form method="post" action="">
            <label>Date:</label>
            <input type="date" name="available_date" required>

            <label>Start Time:</label>
            <input type="time" name="start_time" required>

            <label>End Time:</label>
            <input type="time" name="end_time" required>

            <input type="submit" value="Submit Availability">
        </form>

        <br>
        <a href="schedule-availability.php" class="button">Submit Another</a>
    </div>
</body>
</html>
