document.addEventListener("DOMContentLoaded", function () {
    fetch("/api/courses")
        .then(response => response.json())
        .then(data => {
            const courseList = document.getElementById("course-list");

            data.forEach(course => {
                const div = document.createElement("div");
                div.style.border = "1px solid #ccc";
                div.style.padding = "10px";
                div.style.marginBottom = "10px";

                div.innerHTML = `
                    <strong>${course.code}</strong> - ${course.name} <br>
                    Credits: ${course.credits} <br>
                    Days: ${course.days.join(", ")} <br>
                    Time: ${course.start_time} - ${course.end_time} <br>
                    <button onclick='addCourse(${JSON.stringify(course)})'>Add</button>
                `;

                courseList.appendChild(div);
            });
        });
});

function addCourse(course) {
    fetch("/api/add_course", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(course)
    })
    .then(response => response.json())
    .then(data => {
        alert(data.message);
        location.reload();
    });
}