<?php
// create_schedule.php
// This page allows administrators and instructors to create and manage
// class schedules for courses.

// Ensure session is started.
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Redirect if not logged in OR not an admin/instructor.
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true || ($_SESSION['user_role'] !== 'admin' && $_SESSION['user_role'] !== 'instructor')) {
    header("Location: index.php?page=login");
    exit();
}

require_once 'config/database.php';

$message = '';
$is_error = false;

$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['user_role'];

$courses = []; // Courses available for scheduling

try {
    // Fetch courses based on user role
    $sql_courses = "SELECT id, course_name FROM courses";
    $params = [];
    if ($user_role === 'instructor') {
        $sql_courses .= " WHERE instructor_id = ?";
        $params[] = $user_id;
    }
    $sql_courses .= " ORDER BY course_name ASC";

    $stmt_courses = $pdo->prepare($sql_courses);
    $stmt_courses->execute($params);
    $courses = $stmt_courses->fetchAll(PDO::FETCH_ASSOC);

    if (empty($courses)) {
        $message = "No courses found to create schedules for. Please create a course first.";
        $is_error = true;
    }

} catch (PDOException $e) {
    $message = "Database error fetching courses: " . $e->getMessage();
    $is_error = true;
    error_log("Create Schedule Course Fetch Error: " . $e->getMessage());
}

?>

<div class="w-full max-w-2xl mx-auto p-6 bg-white rounded-lg shadow-xl">
    <h2 class="text-2xl font-bold mb-6 text-center text-gray-800">Create Course Schedule</h2>

    <?php if (!empty($message)): ?>
        <div class="mb-6 p-4 rounded-md text-center text-lg
            <?php echo $is_error ? 'bg-red-100 text-red-700 border border-red-200' : 'bg-blue-50 text-blue-700 border border-blue-200'; ?>">
            <?php echo $message; ?>
            <p class="mt-4"><a href="index.php?page=admin_dashboard" class="text-blue-600 hover:underline">Back to Admin Dashboard</a></p>
        </div>
    <?php endif; ?>

    <?php if (!$is_error && !empty($courses)): ?>
        <form id="createScheduleForm" class="space-y-5">
            <div>
                <label for="course_id" class="block text-gray-700 text-sm font-semibold mb-2">Select Course:</label>
                <select id="course_id" name="course_id" required
                        class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">-- Select a Course --</option>
                    <?php foreach ($courses as $course): ?>
                        <option value="<?php echo htmlspecialchars($course['id']); ?>"><?php echo htmlspecialchars($course['course_name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div>
                <label for="schedule_date" class="block text-gray-700 text-sm font-semibold mb-2">Class Date:</label>
                <input type="date" id="schedule_date" name="schedule_date" required
                       class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>

            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                    <label for="start_time" class="block text-gray-700 text-sm font-semibold mb-2">Start Time:</label>
                    <input type="time" id="start_time" name="start_time" required
                           class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                </div>
                <div>
                    <label for="end_time" class="block text-gray-700 text-sm font-semibold mb-2">End Time:</label>
                    <input type="time" id="end_time" name="end_time" required
                           class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                </div>
            </div>

            <div>
                <label for="topic" class="block text-gray-700 text-sm font-semibold mb-2">Class Topic/Title (Optional):</label>
                <input type="text" id="topic" name="topic"
                       class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                       placeholder="e.g., Introduction to PHP, Module 1 Review">
            </div>

            <div>
                <label for="zoom_link" class="block text-gray-700 text-sm font-semibold mb-2">Zoom/Meeting Link:</label>
                <input type="url" id="zoom_link" name="zoom_link" required
                       class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                       placeholder="https://zoom.us/j/your-meeting-id">
            </div>

            <button type="submit" id="addScheduleButton"
                    class="w-full py-3 px-6 bg-blue-600 text-white font-bold text-lg rounded-md hover:bg-blue-700 transition duration-300 shadow-lg">
                Add Class Schedule
            </button>
        </form>
        <div id="scheduleFormMessage" class="mt-4 text-center text-sm font-semibold"></div>
    <?php endif; ?>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const createScheduleForm = document.getElementById('createScheduleForm');
        const addScheduleButton = document.getElementById('addScheduleButton');
        const scheduleFormMessageDiv = document.getElementById('scheduleFormMessage');

        if (createScheduleForm) {
            createScheduleForm.addEventListener('submit', async function(event) {
                event.preventDefault(); // Prevent default form submission

                const formData = new FormData(this); // Get all form data
                const scheduleData = {};
                for (let [key, value] of formData.entries()) {
                    scheduleData[key] = value;
                }

                addScheduleButton.disabled = true;
                scheduleFormMessageDiv.innerHTML = '<span class="text-blue-600">Adding class schedule...</span>';

                try {
                    const response = await fetch('api/save_schedule.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(scheduleData)
                    });

                    const data = await response.json();

                    if (data.success) {
                        scheduleFormMessageDiv.innerHTML = '<span class="text-green-600">' + data.message + '</span>';
                        createScheduleForm.reset(); // Clear form on success
                    } else {
                        scheduleFormMessageDiv.innerHTML = '<span class="text-red-600">' + (data.message || 'Failed to add schedule. Please try again.') + '</span>';
                    }
                } catch (error) {
                    console.error('Error adding schedule:', error);
                    scheduleFormMessageDiv.innerHTML = '<span class="text-red-600">Network error or server issue. Could not add schedule.</span>';
                } finally {
                    addScheduleButton.disabled = false; // Re-enable button
                }
            });
        }
    });
</script>
