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

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

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

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $date = $_POST['date'] ?? '';
    $start_time = $_POST['start_time'] ?? '';
    $end_time = $_POST['end_time'] ?? '';

    if ($date && $start_time && $end_time) {
        $start = new DateTime($start_time);
        $end = new DateTime($end_time);
        $interval = $start->diff($end);
        $duration_in_hours = $interval->h + ($interval->i / 60);

        if ($duration_in_hours <= 0 || $duration_in_hours > 2) {
            $error = "Each availability slot must be 1 or 2 hours only.";
        } else {
            // Check total hours already scheduled that day
            $stmt_total = $conn->prepare("SELECT start_time, end_time FROM InstructorAvailability WHERE instructor_id = ? AND available_date = ?");
            $stmt_total->bind_param("is", $instructor_id, $date);
            $stmt_total->execute();
            $result = $stmt_total->get_result();
            $total_hours = 0;

            while ($row = $result->fetch_assoc()) {
                $s = new DateTime($row['start_time']);
                $e = new DateTime($row['end_time']);
                $int = $s->diff($e);
                $total_hours += $int->h + ($int->i / 60);
            }

            $stmt_total->close();

            if (($total_hours + $duration_in_hours) > 12) {
                $error = "This slot would exceed your 12-hour daily limit.";
            } else {
                // Check for overlap
                $stmt = $conn->prepare("SELECT id FROM InstructorAvailability WHERE instructor_id = ? AND available_date = ? AND ((start_time <= ? AND end_time > ?) OR (start_time < ? AND end_time >= ?))");
                $stmt->bind_param("isssss", $instructor_id, $date, $start_time, $start_time, $end_time, $end_time);
                $stmt->execute();
                $stmt->store_result();

                if ($stmt->num_rows > 0) {
                    $error = "You already have availability that overlaps with 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_time, $end_time);
                    if ($stmt->execute()) {
                        $success = "Availability added successfully.";
                    } else {
                        $error = "Error adding availability.";
                    }
                    $stmt->close();
                }
            }
        }
    } else {
        $error = "Please fill in all fields.";
    }
}

// Get all availability for this instructor
$availabilities = [];
$stmt = $conn->prepare("SELECT available_date, start_time, end_time FROM InstructorAvailability WHERE instructor_id = ? ORDER BY available_date, start_time");
$stmt->bind_param("i", $instructor_id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $availabilities[] = $row;
}
$stmt->close();
$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Instructor Availability</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            padding: 40px;
        }
        .container {
            background: #fff;
            padding: 25px;
            border-radius: 8px;
            max-width: 500px;
            margin: 0 auto;
            box-shadow: 0px 0px 10px rgba(0,0,0,0.1);
        }
        h2 {
            text-align: center;
        }
        label {
            margin-top: 10px;
            display: block;
        }
        input[type="date"],
        input[type="time"] {
            width: 100%;
            padding: 8px;
            margin-top: 5px;
            border-radius: 4px;
            border: 1px solid #ccc;
        }
        input[type="submit"],
        .button-link {
            display: inline-block;
            margin-top: 20px;
            padding: 10px 15px;
            background: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            text-decoration: none;
            cursor: pointer;
        }
        .button-link:hover {
            background: #0056b3;
        }
        .success { color: green; }
        .error { color: red; }
        table {
            width: 100%;
            margin-top: 25px;
            border-collapse: collapse;
        }
        th, td {
            border: 1px solid #ccc;
            padding: 8px;
            text-align: center;
        }
        th {
            background-color: #eee;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>Submit Weekly Drive Availability</h2>

        <?php if ($success): ?>
            <p class="success"><?php echo $success; ?></p>
            <a href="instructor-availability.php" class="button-link">Submit Another</a>
            <a href="instructor-dashboard.php" class="button-link">Return to Dashboard</a>
        <?php else: ?>
            <?php if ($error): ?><p class="error"><?php echo $error; ?></p><?php endif; ?>
            <form method="post">
                <label for="date">Date:</label>
                <input type="date" name="date" required>

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

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

                <input type="submit" value="Submit Availability">
            </form>
        <?php endif; ?>

        <?php if (!empty($availabilities)): ?>
            <h3>Your Scheduled Availability</h3>
            <table>
                <tr>
                    <th>Date</th>
                    <th>Start</th>
                    <th>End</th>
                </tr>
                <?php foreach ($availabilities as $a): ?>
                <tr>
                    <td><?php echo htmlspecialchars($a['available_date']); ?></td>
                    <td><?php echo htmlspecialchars($a['start_time']); ?></td>
                    <td><?php echo htmlspecialchars($a['end_time']); ?></td>
                </tr>
                <?php endforeach; ?>
            </table>
        <?php endif; ?>
    </div>
</body>
</html>



