{% extends 'template.html' %}

{% block title %}النقاط{% endblock %}

{% block content %}
    <header class="text-center">
        <h1 class="text-3xl sm:text-4xl font-bold text-gray-900 mb-6">نظام النجيب</h1>
        <nav class="mb-8">
            <ul class="flex justify-center space-x-4 space-x-reverse bg-white p-2 rounded-full shadow-lg inline-flex">
                <li>
                    <a href="{{ url_for('index') }}" class="text-gray-700 hover:text-blue-700 hover:bg-blue-50 font-medium px-6 py-3 rounded-full transition-all duration-300 ease-in-out hover:shadow-sm transform hover:scale-105">الصفحة الرئيسية</a>
                </li>
                <li>
                    <a href="{{ url_for('record') }}" class="text-gray-700 hover:text-blue-700 hover:bg-blue-50 font-medium px-6 py-3 rounded-full transition-all duration-300 ease-in-out hover:shadow-sm transform hover:scale-105">تسجيل حضور أو حفظ</a>
                </li>
                <li>
                    <a href="{{ url_for('points') }}" class="text-white bg-blue-600 hover:bg-blue-700 font-semibold px-6 py-3 rounded-full transition-all duration-300 ease-in-out shadow-md">النقاط</a>
                </li>
            </ul>
        </nav>
    </header>

    <div class="bg-white p-8 rounded-xl shadow-lg mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-gray-800 border-b pb-4">إدارة نقاط الطلاب</h2>
        <form id="points-form" action="{{ url_for('points') }}" method="POST">
            <div class="mb-6">
                <label for="search_student_input" class="block text-sm font-medium text-gray-700 mb-1">ابحث عن طالب</label>
                <input type="text" id="search_student_input" placeholder="اكتب اسم الطالب للبحث..."
                       class="w-full px-4 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 text-right" dir="rtl">

                {# Replaced <select> with a div for dynamically generated checkboxes #}
                <div id="student_checkbox_list" class="mt-2 border border-gray-300 rounded-lg p-3 max-h-60 overflow-y-auto bg-gray-50">
                    {# Checkboxes will be inserted here by JavaScript #}
                </div>
                {# Hidden input to mark that at least one student must be selected (will be managed by JS) #}
                <input type="hidden" name="dummy_student_selector" id="dummy_student_selector" value="" required>

                <div class="mt-3 flex items-center">
                    <input type="checkbox" id="select_all_students_checkbox" class="h-4 w-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500">
                    <label for="select_all_students_checkbox" class="ml-2 block text-sm text-gray-900 cursor-pointer">تحديد/إلغاء تحديد الكل</label>
                </div>
            </div>

            <div class="mb-6 flex space-x-4 space-x-reverse">
                <button type="button" id="add-points-btn" data-operation="add" class="flex-1 px-6 py-3 bg-green-600 text-white font-semibold rounded-lg shadow-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 transition-all">
                    إضافة نقاط
                </button>
                <button type="button" id="remove-points-btn" data-operation="remove" class="flex-1 px-6 py-3 bg-red-600 text-white font-semibold rounded-lg shadow-md hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 transition-all">
                    خصم نقاط
                </button>
            </div>

            <div class="mb-6">
                <label for="point_amount" class="block text-sm font-medium text-gray-700 mb-1">المبلغ</label>
                <div class="flex space-x-2 space-x-reverse">
                    <button type="button" class="quick-add-btn px-4 py-2 bg-gray-200 text-gray-700 font-semibold rounded-lg hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-400" data-points="5">5 نقاط</button>
                    <button type="button" class="quick-add-btn px-4 py-2 bg-gray-200 text-gray-700 font-semibold rounded-lg hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-400" data-points="10">10 نقاط</button>
                    <button type="button" class="quick-add-btn px-4 py-2 bg-gray-200 text-gray-700 font-semibold rounded-lg hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-400" data-points="15">15 نقطة</button>
                    <button type="button" class="quick-add-btn px-4 py-2 bg-gray-200 text-gray-700 font-semibold rounded-lg hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-400" data-points="20">20 نقطة</button>
                    <input type="number" name="point_amount" id="point_amount" placeholder="أو أدخل يدوياً" min="1" required class="flex-1 px-4 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 text-right">
                </div>
            </div>

            <input type="hidden" name="operation" id="operation-input">

            <div class="mt-8 text-left">
                <button type="submit" id="submit-points-btn" class="px-8 py-3 bg-blue-600 text-white font-semibold rounded-lg shadow-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-all" disabled>
                    تطبيق النقاط
                </button>
            </div>
        </form>
    </div>

    <script>
        const addPointsBtn = document.getElementById('add-points-btn');
        const removePointsBtn = document.getElementById('remove-points-btn');
        const pointAmountInput = document.getElementById('point_amount');
        const operationInput = document.getElementById('operation-input');
        const submitPointsBtn = document.getElementById('submit-points-btn');
        const quickAddButtons = document.querySelectorAll('.quick-add-btn');

        const searchStudentInput = document.getElementById('search_student_input');
        const studentCheckboxList = document.getElementById('student_checkbox_list');
        const dummyStudentSelector = document.getElementById('dummy_student_selector'); // Hidden input to manage 'required' state

        const selectAllStudentsCheckbox = document.getElementById('select_all_students_checkbox');

        // Store all student data to generate checkboxes dynamically
        // This array will hold objects like { id: 1, name: "Student A", points: 10 }
        const allStudentData = [
            {% for student in students %}
            { id: {{ student.id }}, name: "{{ student.student_name }}", points: {{ student.points }} },
            {% endfor %}
        ];

        // Store the state of checkboxes across filters
        const selectedStudentIds = new Set(); // Use a Set for efficient ID tracking

        // Function to perform a fuzzy match
        function fuzzyMatch(pattern, text) {
            pattern = pattern.toLowerCase();
            text = text.toLowerCase();
            let patternIdx = 0;
            let textIdx = 0;

            while (patternIdx < pattern.length && textIdx < text.length) {
                if (pattern[patternIdx] === text[textIdx]) {
                    patternIdx++;
                }
                textIdx++;
            }
            return patternIdx === pattern.length;
        }

        // Function to render/filter the student checkboxes
        function renderStudentCheckboxes() {
            const searchTerm = searchStudentInput.value.trim();
            studentCheckboxList.innerHTML = ''; // Clear current checkboxes

            let studentsFound = 0;

            allStudentData.forEach(student => {
                const studentName = student.name;
                const matchesSearch = searchTerm === '' || fuzzyMatch(searchTerm, studentName);

                if (matchesSearch) {
                    studentsFound++;
                    const checkboxId = `student_id_${student.id}`;
                    const div = document.createElement('div');
                    div.className = 'flex items-center py-1'; // Add some padding

                    const input = document.createElement('input');
                    input.type = 'checkbox';
                    input.name = 'student_id'; // Important: all checkboxes have the same name
                    input.value = student.id;
                    input.id = checkboxId;
                    input.className = 'h-4 w-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500 cursor-pointer';

                    const label = document.createElement('label');
                    label.htmlFor = checkboxId;
                    label.className = 'ml-2 block text-sm text-gray-900 cursor-pointer flex-1';
                    label.textContent = `${student.name} (النقاط الحالية: ${student.points})`;

                    // Restore selection state
                    if (selectedStudentIds.has(student.id)) {
                        input.checked = true;
                    }

                    // Add event listener directly to the checkbox
                    input.addEventListener('change', (event) => {
                        if (event.target.checked) {
                            selectedStudentIds.add(student.id);
                        } else {
                            selectedStudentIds.delete(student.id);
                        }
                        // Update select all checkbox status
                        updateSelectAllCheckboxState();
                        updateSubmitButtonState();
                    });

                    div.appendChild(input);
                    div.appendChild(label);
                    studentCheckboxList.appendChild(div);
                }
            });

            if (studentsFound === 0 && searchTerm !== '') {
                studentCheckboxList.innerHTML = '<p class="text-gray-500 text-sm p-2">لا توجد نتائج بحث مطابقة.</p>';
            }

            updateSelectAllCheckboxState(); // Update select all checkbox based on current filtered view
            updateSubmitButtonState(); // Update submit button state
        }

        // Function to update the "Select All" checkbox state
        function updateSelectAllCheckboxState() {
            const visibleCheckboxes = Array.from(studentCheckboxList.querySelectorAll('input[type="checkbox"]'));
            if (visibleCheckboxes.length === 0) {
                selectAllStudentsCheckbox.checked = false;
                selectAllStudentsCheckbox.disabled = true;
            } else {
                selectAllStudentsCheckbox.disabled = false;
                const allVisibleChecked = visibleCheckboxes.every(cb => cb.checked);
                selectAllStudentsCheckbox.checked = allVisibleChecked;
            }
        }

        // Function to update the submit button state
        function updateSubmitButtonState() {
            // Now, we just check if any checkbox is selected (using our Set)
            const studentsSelected = selectedStudentIds.size > 0;
            const amountEntered = pointAmountInput.value.trim() !== '' && parseInt(pointAmountInput.value) > 0;
            const operationSelected = operationInput.value !== '';

            if (studentsSelected && amountEntered && operationSelected) {
                submitPointsBtn.disabled = false;
                submitPointsBtn.classList.remove('bg-gray-400', 'hover:bg-gray-500');
                submitPointsBtn.classList.add('bg-blue-600', 'hover:bg-blue-700');
                dummyStudentSelector.removeAttribute('required'); // Allow submission
            } else {
                submitPointsBtn.disabled = true;
                submitPointsBtn.classList.remove('bg-blue-600', 'hover:bg-blue-700');
                submitPointsBtn.classList.add('bg-gray-400', 'hover:bg-gray-500');
                dummyStudentSelector.setAttribute('required', 'required'); // Prevent submission
            }
        }

        // Event listener for "Select All" checkbox
        selectAllStudentsCheckbox.addEventListener('change', () => {
            const isChecked = selectAllStudentsCheckbox.checked;
            studentCheckboxList.querySelectorAll('input[type="checkbox"]').forEach(checkbox => {
                checkbox.checked = isChecked;
                // Manually update the selectedStudentIds set
                if (isChecked) {
                    selectedStudentIds.add(parseInt(checkbox.value));
                } else {
                    selectedStudentIds.delete(parseInt(checkbox.value));
                }
            });
            updateSubmitButtonState();
        });


        // Event listeners for Add/Remove buttons
        addPointsBtn.addEventListener('click', () => {
            operationInput.value = 'add';
            addPointsBtn.classList.add('bg-green-700');
            removePointsBtn.classList.remove('bg-red-700');
            updateSubmitButtonState();
        });

        removePointsBtn.addEventListener('click', () => {
            operationInput.value = 'remove';
            removePointsBtn.classList.add('bg-red-700');
            addPointsBtn.classList.remove('bg-green-700');
            updateSubmitButtonState();
        });

        // Event listener for quick add buttons
        quickAddButtons.forEach(button => {
            button.addEventListener('click', () => {
                pointAmountInput.value = button.dataset.points;
                updateSubmitButtonState();
            });
        });

        // Event listener for manual input change
        pointAmountInput.addEventListener('input', updateSubmitButtonState);

        // Event listener for search input
        searchStudentInput.addEventListener('input', renderStudentCheckboxes);

        // Initial setup on page load
        renderStudentCheckboxes(); // Render initial list of all students
        updateSubmitButtonState(); // Set initial button state

        // Prevent double submission
        const pointsForm = document.getElementById('points-form');
        if (pointsForm) {
            pointsForm.addEventListener('submit', () => {
                submitPointsBtn.disabled = true;
                submitPointsBtn.textContent = 'جاري المعالجة...';
            });
        }
    </script>
{% endblock %}
