document.addEventListener('DOMContentLoaded', () => {
    const contentContainer = document.getElementById('content-container');
    const mainContainer = document.createElement('div');
	mainContainer.classList.add('content-container-container');
    const scheduleNav = document.createElement('div');
    scheduleNav.classList.add('schedule-navigation');
    const prevDayButton = document.createElement('button');
    prevDayButton.id = 'prev-day';
    prevDayButton.textContent = '<';
    scheduleNav.appendChild(prevDayButton);
    const datePicker = document.createElement('input');
    datePicker.id = 'date-picker';
    datePicker.type = 'date';
    scheduleNav.appendChild(datePicker);
    const nextDayButton = document.createElement('button');
    nextDayButton.id = 'next-day';
    nextDayButton.textContent = '>';
    scheduleNav.appendChild(nextDayButton);
    mainContainer.appendChild(scheduleNav);
    const scheduleTableContainer = document.createElement('div');
    scheduleTableContainer.id = 'schedule-table-container';
    mainContainer.appendChild(scheduleTableContainer);
    contentContainer.appendChild(mainContainer);
    let sessionUserId = null;
    let userLevel = null;
    let userClassId = null;
    let selectedDate = new Date().toISOString().split('T')[0];
    let selectedClassId = null;
    const classDropdown = document.createElement('select');
    const getSessionUserId = async () => {
        try {
            const response = await fetch('../php/get_session_user.php');
            const data = await response.json();
            sessionUserId = data.user_id;
            userLevel = data.user_level;
            userClassId = data.class_id;
            if (userLevel === 3) {
                await getAllClasses();
                scheduleNav.appendChild(classDropdown);
                classDropdown.addEventListener('change', () => {
                    selectedClassId = classDropdown.value;
                    getSchedule(selectedDate, selectedClassId);
                });
            }
        } catch (error) {
            console.error('Error fetching session user ID:', error);
        }
    };
    const getAllClasses = async () => {
        try {
            const response = await fetch('../php/get_all_classes.php');
            const data = await response.json();
            
            if (data.success) {
                classDropdown.innerHTML = '<option value="">Izvēlies grupu</option>';
                data.classes.forEach(cls => {
                    const option = document.createElement('option');
                    option.value = cls.id;
                    option.textContent = cls.class_name;
                    classDropdown.appendChild(option);
                });
            }
        } catch (error) {
            console.error('Error fetching classes:', error);
        }
    };
   const getSchedule = async (date, classId = userClassId) => {
        if (!userLevel || !sessionUserId) {
            console.error('User level or ID is missing');
            return;
        }
        try {
            const response = await fetch(`../php/fetch_schedule.php?user_level=${userLevel}&user_id=${sessionUserId}&class_id=${classId || ''}&date=${date}`);
            const data = await response.json();
            if (data.success) {
                displaySchedule(data.schedule, date);
            } else {
                displaySchedule([], date);
            }
        } catch (error) {
            console.error('Error fetching schedule:', error);
        }
    };
const displaySchedule = (schedule, date) => {
    scheduleTableContainer.innerHTML = '';
    const table = document.createElement('table');
    table.className = 'schedule-table';
    const headers = ['Laiki', 'Priekšmets'];
    if (userLevel !== 1) headers.push('Grupa');
    if (userLevel !== 2) headers.push('Pasniedzējs');
    headers.push('Telpa');
    if (userLevel === 3) headers.push('Dzēst');
    const headerRow = document.createElement('tr');
    headers.forEach(headerText => {
        const th = document.createElement('th');
        th.textContent = headerText;
        headerRow.appendChild(th);
    });
    table.appendChild(headerRow);
    const scheduleTimes = [
        '8:30-9:10', '9:10-9:50', '10:00-10:40', '10:40-11:20',
        '11:20-12:00',
        '12:10-12:50', '12:50-13:30', '13:40-14:20', '14:20-15:00'
    ];
    scheduleTimes.forEach((time, index) => {
        const row = document.createElement('tr');
        row.classList.add('schedule-row');
        if (time === '11:20-12:00') {
            const breakCell = document.createElement('td');
            breakCell.colSpan = headers.length;
            breakCell.textContent = 'Starpbrīdis';
            row.appendChild(breakCell);
        } else {
            const timeCell = document.createElement('td');
            timeCell.textContent = time;
            row.appendChild(timeCell);
            const adjustedIndex = index > 4 ? index - 1 : index;
            const scheduleItem = schedule.find(item => item.position === adjustedIndex + 1);
            const subjectCell = document.createElement('td');
            subjectCell.textContent = scheduleItem ? scheduleItem.subject_name : '';
            row.appendChild(subjectCell);
            if (userLevel !== 1) {
                const classCell = document.createElement('td');
                classCell.textContent = scheduleItem ? scheduleItem.class_name : '';
                row.appendChild(classCell);
            }
            if (userLevel !== 2) {
                const teacherCell = document.createElement('td');
                teacherCell.textContent = scheduleItem ? scheduleItem.teacher_name : '';
                row.appendChild(teacherCell);
            }
            const roomCell = document.createElement('td');
            roomCell.textContent = scheduleItem ? scheduleItem.room_number : '';
            row.appendChild(roomCell);
            if (userLevel === 3) {
                const actionsCell = document.createElement('td');
                if (scheduleItem?.id) {
                    const deleteButton = document.createElement('span');
                    deleteButton.textContent = 'X';
                    deleteButton.style.cursor = 'pointer';
                    deleteButton.style.color = 'red';
                    deleteButton.style.fontWeight = 'bold';
                    deleteButton.addEventListener('click', (event) => {
                        event.stopPropagation();
                        deleteSchedule(scheduleItem.id);
                    });

                    actionsCell.appendChild(deleteButton);
                }
                row.appendChild(actionsCell);
            }
            row.dataset.scheduleData = JSON.stringify({
                id: scheduleItem?.id || null,
                time,
                position: scheduleItem?.position || adjustedIndex + 1,
                subject: scheduleItem?.subject_name || '',
                class: scheduleItem?.class_name || '',
                teacher: scheduleItem?.teacher_name || '',
                room: scheduleItem?.room_number || ''
            });
            if (userLevel === 3) {
                row.addEventListener('click', () => {
                    openModal(JSON.parse(row.dataset.scheduleData));
                });
            }
        }
        table.appendChild(row);
    });
    scheduleTableContainer.appendChild(table);
};
const deleteSchedule = async (scheduleId) => {
    try {
        const response = await fetch('../php/delete_schedule.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ id: scheduleId })
        });
        const result = await response.json();
        if (result.success) {
            alert(result.message);
            getSchedule(selectedDate, selectedClassId || userClassId);
        } else {
            alert(result.message || 'Failed to delete schedule.');
        }
    } catch (error) {
        console.error('Error deleting schedule:', error);
        alert('An error occurred while deleting the schedule.');
    }
};
const fetchDropdownData = async (endpoint) => {
    try {
        const response = await fetch(endpoint);
        return await response.json();
    } catch (error) {
        console.error(`Error fetching data from ${endpoint}:`, error);
        return [];
    }
};
const openModal = async (rowData) => {
    const subjects = await fetchDropdownData('../php/get_subjects.php');
    const teachers = await fetchDropdownData('../php/get_teachers.php');
    const rooms = await fetchDropdownData('../php/get_rooms.php');
    let modal = document.getElementById('dynamic-schedule-modal');
    if (!modal) {
        modal = document.createElement('div');
        modal.id = 'dynamic-schedule-modal';
        const modalContent = document.createElement('div');
        modalContent.className = 'modal-content';
        const closeModal = document.createElement('button');
        closeModal.className = 'close-modal-btn';
        closeModal.textContent = '×';
        closeModal.addEventListener('click', () => {
            modal.style.display = 'none';
        });
        modalContent.appendChild(closeModal);
        modal.appendChild(modalContent);
        document.body.appendChild(modal);
    }
    const modalContent = modal.querySelector('.modal-content');
    modalContent.innerHTML = `
        <button class="close-modal-btn">×</button>
        <p><strong>Time:</strong> ${rowData.time}</p>
        <label for="subject-select">Subject:</label>
        <select id="subject-select">${subjects
            .map(subject => `<option value="${subject.id}" ${subject.name === rowData.subject ? 'selected' : ''}>${subject.name}</option>`)
            .join('')}</select>
        <label for="teacher-select">Teacher:</label>
        <select id="teacher-select">${teachers
            .map(teacher => `<option value="${teacher.id}" ${teacher.username === rowData.teacher ? 'selected' : ''}>${teacher.username}</option>`)
            .join('')}</select>
        <label for="room-select">Room:</label>
        <select id="room-select">${rooms
            .map(room => `<option value="${room.id}" ${room.room_number === rowData.room ? 'selected' : ''}>${room.room_number}</option>`)
            .join('')}</select>
        <button id="save-changes">Save Changes</button>
    `;
    const closeModal = modalContent.querySelector('.close-modal-btn');
    closeModal.addEventListener('click', () => {
        modal.style.display = 'none';
    });
    document.getElementById('save-changes').addEventListener('click', async () => {
        const updatedData = {
            id: rowData.id,
            class_id: selectedClassId || userClassId,
            date: selectedDate,
            position: rowData.position,
            subject_id: document.getElementById('subject-select').value,
            teacher_id: document.getElementById('teacher-select').value,
            room_id: document.getElementById('room-select').value
        };
        try {
            const response = await fetch('../php/update_schedule.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(updatedData)
            });
            const result = await response.json();
            if (result.success) {
                alert(result.message);
                modal.style.display = 'none';
                getSchedule(selectedDate, selectedClassId || userClassId);
            } else {
                alert(result.message || 'Failed to update or insert schedule.');
            }
        } catch (error) {
            console.error('Error saving schedule:', error);
        }
    });
    modal.style.display = 'block';
};
    const updateContent = (content) => {
        if (content === 'schedule') {
            contentContainer.innerHTML = ''; 
            contentContainer.appendChild(mainContainer);
            getSchedule(selectedDate, selectedClassId || userClassId);
        }
    };
    const savedContent = localStorage.getItem('selectedContent') || 'feed';
    getSessionUserId().then(() => {
        updateContent(savedContent);
    });
    document.querySelectorAll('.sidebar button').forEach(button => {
        button.addEventListener('click', (event) => {
            const content = event.target.getAttribute('data-content');
            if (content) {
                updateContent(content);
                localStorage.setItem('selectedContent', content);
            }
        });
    });
    datePicker.addEventListener('change', (event) => {
        selectedDate = event.target.value;
        getSchedule(selectedDate, selectedClassId || userClassId);
    });
    prevDayButton.addEventListener('click', () => {
        const prevDate = new Date(selectedDate);
        prevDate.setDate(prevDate.getDate() - 1);
        selectedDate = prevDate.toISOString().split('T')[0];
        datePicker.value = selectedDate;
        getSchedule(selectedDate, selectedClassId || userClassId);
    });
    nextDayButton.addEventListener('click', () => {
        const nextDate = new Date(selectedDate);
        nextDate.setDate(nextDate.getDate() + 1);
        selectedDate = nextDate.toISOString().split('T')[0];
        datePicker.value = selectedDate;
        getSchedule(selectedDate, selectedClassId || userClassId);
    });
});