document.addEventListener('DOMContentLoaded', () => {
    const contentContainer = document.getElementById('content-container');
    let sessionUserId = null;
    let userLevel = null;
const displayAddTestModal = () => {
    let modal = document.getElementById('add-test-modal');
    if (!modal) {
        modal = document.createElement('div');
        modal.id = 'add-test-modal';
        modal.className = 'modal';
        document.body.appendChild(modal);

        modal.innerHTML = `
            <div class="modal-content">
                <span id="close-test-modal" class="close-modal">&times;</span>
                <h3>Pievienot pārbaudes darbu</h3>
                <form id="add-test-form">
                    <label for="test_name">Pārbaudes darba nosaukums:</label>
                    <input type="text" id="test_name" name="test_name" required />

                    <button type="submit">Pievienot</button>
                </form>
            </div>
        `;

        const closeModal = document.getElementById('close-test-modal');
        closeModal.addEventListener('click', () => {
            modal.style.display = 'none';
        });

        const form = document.getElementById('add-test-form');
        form.addEventListener('submit', async (e) => {
            e.preventDefault();

            const formData = new FormData(form);
            formData.append('teacher_id', sessionUserId);

            try {
                const response = await fetch('../php/add_test.php', {
                    method: 'POST',
                    body: formData,
                });

                const result = await response.json();
                if (result.success) {
                    form.reset();
                    modal.style.display = 'none';
					loadSelectors();
                } else {
                    alert(`Error: ${result.message}`);
                }
            } catch (error) {
                console.error('Error adding test:', error);
            }
        });
    }

    modal.style.display = 'block';
};

const addTestButton = () => {
    const addTestBtn = document.createElement('button');
    addTestBtn.textContent = 'Pievienot Pārbaudes darbu';
    addTestBtn.addEventListener('click', displayAddTestModal);
    contentContainer.appendChild(addTestBtn);
};

const loadStudentGrades = async (studentId) => {
    try {
        let marksContainer = document.getElementById('marks-container');
        if (!marksContainer) {
            marksContainer = document.createElement('div');
            marksContainer.id = 'marks-container';
            contentContainer.appendChild(marksContainer);
        }

        marksContainer.innerHTML = '';


        let selectorsContainer = document.getElementById('selectors-container');
        if (!selectorsContainer) {
            selectorsContainer = document.createElement('div');
            selectorsContainer.id = 'selectors-container';
            marksContainer.appendChild(selectorsContainer);
        } else {
            selectorsContainer.innerHTML = '';
        }

        const subjectResponse = await fetch('../php/get_subjects.php');
        const subjectData = await subjectResponse.json();

        if (subjectData && Array.isArray(subjectData)) {

            const subjectFilter = document.createElement('select');
            subjectFilter.id = 'subject-filter';
            const defaultOption = document.createElement('option');
            defaultOption.value = '';
            defaultOption.textContent = 'Visi priekšmeti';
            subjectFilter.appendChild(defaultOption);

            subjectData.forEach((subject) => {
                const option = document.createElement('option');
                option.value = subject.id;
                option.textContent = subject.name;
                subjectFilter.appendChild(option);
            });

            selectorsContainer.appendChild(subjectFilter);

            subjectFilter.addEventListener('change', async () => {
                const selectedSubject = subjectFilter.value;
                await fetchAndDisplayGrades(studentId, selectedSubject);
            });
        }

        await fetchAndDisplayGrades(studentId);
    } catch (error) {
        console.error('Error loading student grades:', error);
    }
};

const fetchAndDisplayGrades = async (studentId, subjectId = '') => {
    try {
        const queryParams = new URLSearchParams({
            student_id: studentId,
            user_level: userLevel,
            ...(subjectId && { subject_id: subjectId }),
        });

        const response = await fetch(`../php/get_grades.php?${queryParams.toString()}`);
        const data = await response.json();

        const gradesList = document.getElementById('grades-list');
        if (!gradesList) {
            const newGradesList = document.createElement('div');
            newGradesList.id = 'grades-list';
            document.getElementById('marks-container').appendChild(newGradesList);
        } else {
            gradesList.innerHTML = '';
        }

        if (data.success && data.grades.length > 0) {
            const gradesList = document.getElementById('grades-list');
            data.grades.forEach((grade) => {
                const gradeCard = document.createElement('div');
                gradeCard.className = 'grade-card';
                gradeCard.innerHTML = `
                    <p><strong>Vērtējums:</strong> ${grade.grade}</p>
                    <p><strong>Priekšmets:</strong> ${grade.subject_name}</p>
                    <p><strong>Pārbaudes darbs:</strong> ${grade.test_name}</p>
                    <p><strong>Datums:</strong> ${new Date(grade.date).toLocaleDateString()}</p>
                `;
                gradesList.appendChild(gradeCard);
            });
        } else {
            const noGradesMessage = document.createElement('p');
            noGradesMessage.textContent = 'Nav pieejams neviens vērtējums.';
            document.getElementById('grades-list').appendChild(noGradesMessage);
        }
    } catch (error) {
        console.error('Error fetching grades:', error);
    }
};

const loadSelectors = async () => {
    try {
        const response = await fetch(`../php/get_classes_and_tests.php${userLevel === 2 ? `?teacher_id=${sessionUserId}` : ''}`);
        const data = await response.json();

        if (data.success) {
            let selectorsContainer = document.getElementById('selectors-container');
            if (!selectorsContainer) {
                selectorsContainer = document.createElement('div');
                selectorsContainer.id = 'selectors-container';
                contentContainer.insertBefore(selectorsContainer, contentContainer.firstChild);
            }

            selectorsContainer.innerHTML = '';

            const classSelectorWrapper = document.createElement('div');
            classSelectorWrapper.className = 'selector-wrapper';

            const classSelectorLabel = document.createElement('label');
            classSelectorLabel.textContent = 'Grupa: ';
            classSelectorWrapper.appendChild(classSelectorLabel);

            const classSelector = document.createElement('select');
            classSelector.id = 'class-selector';
            const defaultClassOption = document.createElement('option');
            defaultClassOption.value = '';
            defaultClassOption.textContent = 'Visas grupas';
            classSelector.appendChild(defaultClassOption);
            data.classes.forEach((classData) => {
                const option = document.createElement('option');
                option.value = classData.id;
                option.textContent = classData.class_name;
                classSelector.appendChild(option);
            });
            classSelectorWrapper.appendChild(classSelector);

            selectorsContainer.appendChild(classSelectorWrapper);

            const testSelectorWrapper = document.createElement('div');
            testSelectorWrapper.className = 'selector-wrapper';

            const testSelectorLabel = document.createElement('label');
            testSelectorLabel.textContent = 'Pārbaudes darbs: ';
            testSelectorWrapper.appendChild(testSelectorLabel);

            const testSelector = document.createElement('select');
            testSelector.id = 'test-selector';
            const defaultTestOption = document.createElement('option');
            defaultTestOption.value = '';
            defaultTestOption.textContent = 'Visi pārbaudes darbi';
            testSelector.appendChild(defaultTestOption);
            data.tests.forEach((testData) => {
                const option = document.createElement('option');
                option.value = testData.id;
                option.textContent = testData.name;
                testSelector.appendChild(option);
            });
            testSelectorWrapper.appendChild(testSelector);

            selectorsContainer.appendChild(testSelectorWrapper);

            classSelector.addEventListener('change', () => {
                loadTeacherGrades(userLevel === 2 ? sessionUserId : null, classSelector.value, testSelector.value);
            });
            testSelector.addEventListener('change', () => {
                loadTeacherGrades(userLevel === 2 ? sessionUserId : null, classSelector.value, testSelector.value);
            });
        }
    } catch (error) {
        console.error('Error loading selectors:', error);
    }
};

const deleteGrade = async (gradeId) => {
    try {
        const response = await fetch('../php/delete_grade.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ grade_id: gradeId }),
        });

        const result = await response.json();
        if (result.success) {
            alert('Vērtējums dzēsts!');
            const classId = document.getElementById('class-selector').value || '';
            const testId = document.getElementById('test-selector').value || '';
            loadTeacherGrades(sessionUserId, classId, testId);
        } else {
            alert(`Error: ${result.message}`);
        }
    } catch (error) {
        console.error('Error deleting grade:', error);
    }
};

const loadTeacherGrades = async (teacherId = null, classId = '', testId = '') => {
    try {
        let tableContainer = document.getElementById('grades-table-container');
        if (!tableContainer) {
            tableContainer = document.createElement('div');
            tableContainer.id = 'grades-table-container';
            contentContainer.appendChild(tableContainer);
        }

        tableContainer.innerHTML = '';

        if (userLevel === 2) {
            let actionsContainer = document.getElementById('actions-container');
            if (!actionsContainer) {
                actionsContainer = document.createElement('div');
                actionsContainer.id = 'actions-container';
                actionsContainer.className = 'actions-container';
                contentContainer.insertBefore(actionsContainer, tableContainer);

                const addGradeButton = document.createElement('button');
                addGradeButton.textContent = 'Pievienot vērtējumu';
                addGradeButton.addEventListener('click', displayAddGradeModal);
                actionsContainer.appendChild(addGradeButton);

                const addTestButton = document.createElement('button');
                addTestButton.textContent = 'Pievienot pārbaudes darbu';
                addTestButton.addEventListener('click', displayAddTestModal);
                actionsContainer.appendChild(addTestButton);

                const deleteTestsButton = document.createElement('button');
                deleteTestsButton.textContent = 'Dzēst pārbaudes darbu';
                deleteTestsButton.addEventListener('click', displayDeleteTestsModal);
                actionsContainer.appendChild(deleteTestsButton);
            }
        }

        const queryParams = new URLSearchParams({
            user_level: userLevel,
            ...(teacherId ? { teacher_id: teacherId } : {}),
            class_id: classId,
            test_id: testId,
        });

        const response = await fetch(`../php/get_grades.php?${queryParams.toString()}`);
        const data = await response.json();

        if (data.success && data.grades.length > 0) {
            const table = document.createElement('table');
            table.className = 'grades-table';

            const headers = ['Vērtējums', 'Priekšmets', 'Pārbaudes darbs', 'Skolnieks', 'Datums', 'Dzēst'];
            const thead = document.createElement('thead');
            const headerRow = document.createElement('tr');

            headers.forEach((headerText) => {
                const th = document.createElement('th');
                th.textContent = headerText;
                headerRow.appendChild(th);
            });
            thead.appendChild(headerRow);
            table.appendChild(thead);

            const tbody = document.createElement('tbody');
            data.grades.forEach((grade) => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${grade.grade}</td>
                    <td>${grade.subject_name}</td>
                    <td>${grade.test_name}</td>
                    <td>${grade.student_name}</td>
                    <td>${new Date(grade.date).toLocaleDateString()}</td>
                    ${
                        userLevel === 2
                            ? `<td><button class="delete-grade-btn" data-id="${grade.id}">Delete</button></td>`
                            : `<td>-</td>`
                    }
                `;
                tbody.appendChild(row);
            });
            table.appendChild(tbody);
            tableContainer.appendChild(table);

            if (userLevel === 2) {
                document.querySelectorAll('.delete-grade-btn').forEach((button) => {
                    button.addEventListener('click', (e) => {
                        const gradeId = e.target.getAttribute('data-id');
                        deleteGrade(gradeId);
                    });
                });
            }
        } else {
            const noGradesMessage = document.createElement('p');
            noGradesMessage.textContent = 'No grades available.';
            tableContainer.appendChild(noGradesMessage);
        }
    } catch (error) {
        console.error('Error fetching grades:', error);
    }
};

const displayAddGradeModal = () => {
    let modal = document.getElementById('add-grade-modal');
    if (!modal) {
        modal = document.createElement('div');
        modal.id = 'add-grade-modal';
        modal.className = 'modal';
        document.body.appendChild(modal);

        modal.innerHTML = `
            <div class="modal-content">
                <span id="close-modal" class="close-modal">&times;</span>
                <h3>Pievienot Vērtējumu</h3>
                <form id="add-grade-form">
                    <label for="class_id">Grupa:</label>
                    <select id="class_id" name="class_id" required></select>

                    <label for="student_id">Skolnieks:</label>
                    <select id="student_id" name="student_id" required></select>

                    <label for="subject_id">Priekšmets:</label>
                    <select id="subject_id" name="subject_id" required></select>

                    <label for="test_id">Pārbaudes darbs:</label>
                    <select id="test_id" name="test_id" required></select>

                    <label for="grade">Vērtējums:</label>
                    <input type="text" id="grade" name="grade" required />

                    <label for="date">Datums:</label>
                    <input type="date" id="date" name="date" value="${new Date().toISOString().split('T')[0]}" />

                    <button type="submit">Pievienot</button>
                </form>
            </div>
        `;

        const closeModal = document.getElementById('close-modal');
        closeModal.addEventListener('click', () => {
            modal.style.display = 'none';
        });

        const form = document.getElementById('add-grade-form');
        form.addEventListener('submit', async (e) => {
            e.preventDefault();

            const formData = new FormData(form);
            formData.append('teacher_id', sessionUserId);

            try {
                const response = await fetch('../php/add_grade.php', {
                    method: 'POST',
                    body: formData,
                });

                const result = await response.json();
                if (result.success) {
                    alert('Vērtējums pievienots!');
                    form.reset();
                    modal.style.display = 'none';

                    const classId = document.getElementById('class_id').value || '';
                    const testId = document.getElementById('test_id').value || '';
                    loadTeacherGrades(sessionUserId, classId, testId);
                } else {
                    alert(`Error: ${result.message}`);
                }
            } catch (error) {
                console.error('Error adding grade:', error);
            }
        });

        populateClassDropdown();
        populateSubjectDropdown();
        populateTestDropdown();

        document.getElementById('class_id').addEventListener('change', (e) => {
            populateStudentDropdown(e.target.value);
        });
    }

    modal.style.display = 'block';
};

const populateClassDropdown = async () => {
    try {
        const response = await fetch('../php/get_all_classes.php');
        const data = await response.json();
        const classSelect = document.getElementById('class_id');
        classSelect.innerHTML = '<option value="">Izvēlaties grupu</option>';
        data.classes.forEach((cls) => {
            const option = document.createElement('option');
            option.value = cls.id;
            option.textContent = cls.class_name;
            classSelect.appendChild(option);
        });
    } catch (error) {
        console.error('Error fetching classes:', error);
    }
};

const populateStudentDropdown = async (classId) => {
    try {
        const response = await fetch(`../php/get_students_by_class.php?class_id=${classId}`);
        const data = await response.json();
        const studentSelect = document.getElementById('student_id');
        studentSelect.innerHTML = '<option value="">Izvēlaties skolnieku</option>';
        data.students.forEach((student) => {
            const option = document.createElement('option');
            option.value = student.id;
            option.textContent = student.username;
            studentSelect.appendChild(option);
        });
    } catch (error) {
        console.error('Error fetching students:', error);
    }
};
const populateSubjectDropdown = async () => {
    try {
        const response = await fetch('../php/get_subjects.php');
        const data = await response.json();

        if (Array.isArray(data)) {
            const subjectSelect = document.getElementById('subject_id');
            subjectSelect.innerHTML = '<option value="">Izvēlaties priekšmetu</option>';

            data.forEach((subject) => {
                const option = document.createElement('option');
                option.value = subject.id;
                option.textContent = subject.name;
                subjectSelect.appendChild(option);
            });
        } else if (data.success === false) {
            console.error('Error fetching subjects:', data.message);
        }
    } catch (error) {
        console.error('Error fetching subjects:', error);
    }
};
const populateTestDropdown = async () => {
    try {
        const response = await fetch(`../php/get_tests.php?teacher_id=${sessionUserId}`);
        const data = await response.json();
        const testSelect = document.getElementById('test_id');
        testSelect.innerHTML = '<option value="">Izvēlaties pārbaudes darbu</option>';
        if (data.success && Array.isArray(data.tests)) {
            data.tests.forEach((test) => {
                const option = document.createElement('option');
                option.value = test.id;
                option.textContent = test.name;
                testSelect.appendChild(option);
            });
        } else {
            testSelect.innerHTML = '<option value="">Nav pieejams neviens pārbaudes darbs</option>';
        }
    } catch (error) {
        console.error('Error fetching tests:', error);
    }
};

const displayDeleteTestsModal = () => {
    let modal = document.getElementById('delete-tests-modal');
    if (!modal) {
        modal = document.createElement('div');
        modal.id = 'delete-tests-modal';
        modal.className = 'modal';
        document.body.appendChild(modal);

        modal.innerHTML = `
            <div class="modal-content">
                <span id="close-delete-tests-modal" class="close-modal">&times;</span>
                <h3>Dzēst Pārbaudes darbu</h3>
                <div id="tests-list-container"></div>
            </div>
        `;

        const closeModal = document.getElementById('close-delete-tests-modal');
        closeModal.addEventListener('click', () => {
            modal.style.display = 'none';
        });
    }

    modal.style.display = 'block';

    populateTestsListForDeletion();
};
const deleteTest = async (testId) => {
    try {
        const response = await fetch('../php/delete_test.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ test_id: testId }),
        });

        const result = await response.json();
        if (result.success) {
            populateTestsListForDeletion();
			loadSelectors();
        } else {
            alert(`Error: ${result.message}`);
        }
    } catch (error) {
        console.error('Error deleting test:', error);
    }
};


const populateTestsListForDeletion = async () => {
    const testsListContainer = document.getElementById('tests-list-container');
    if (!testsListContainer) return;

    testsListContainer.innerHTML = '';

    try {
        const response = await fetch(`../php/get_tests.php?teacher_id=${sessionUserId}`);
        const data = await response.json();

        if (data.success && Array.isArray(data.tests) && data.tests.length > 0) {
            data.tests.forEach((test) => {
                const testItem = document.createElement('div');
                testItem.className = 'test-item';
                testItem.innerHTML = `
                    <span>${test.name}</span>
                    <button class="delete-test-btn" data-id="${test.id}">Dzēst</button>
                `;
                testsListContainer.appendChild(testItem);

                testItem.querySelector('.delete-test-btn').addEventListener('click', () => {
                    deleteTest(test.id);
                });
            });
        } else {
            testsListContainer.innerHTML = '<p>Nav pieejams neviens pārbaudes darbs ko dzēst</p>';
        }
    } catch (error) {
        console.error('Error fetching tests for deletion:', error);
        testsListContainer.innerHTML = '<p>Error loading tests. Please try again later.</p>';
    }
};
const updateContent = (content) => {
    if (content === 'marks') {
        contentContainer.innerHTML = '';
        if (userLevel === 1) {
            if (sessionUserId) {
                loadStudentGrades(sessionUserId);
            } else {
                console.error('Student ID is not available.');
            }
        } else if (userLevel === 2 || userLevel === 3) {
            if (sessionUserId) {
                loadSelectors();
                loadTeacherGrades(sessionUserId);
            } else {
                console.error('Teacher/Admin ID is not available.');
            }
        }
    }
};

    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;
        } catch (error) {
            console.error('Error fetching session user ID:', error);
        }
    };

    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);
            }
        });
    });

});
