{% 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-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>
                <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-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>
            </ul>
        </nav>
    </header>

    <div id="add-student-section" class="bg-white p-8 rounded-xl shadow-lg mb-8 hidden">
        <h2 class="text-2xl font-semibold mb-6 text-gray-800 border-b pb-4">إضافة طالب جديد</h2>
        <form id="add-student-form" action="{{ url_for('add_student') }}" method="POST">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-x-8 gap-y-6">
                <div>
                    <label for="student_name" class="block text-sm font-medium text-gray-700 mb-1">اسم الطالب</label>
                    <input type="text" name="student_name" id="student_name" placeholder="الاسم الكامل" required 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">
                </div>
                <div>
                    <label for="age" class="block text-sm font-medium text-gray-700 mb-1">العمر</label>
                    <input type="number" name="age" id="age" placeholder="مثال: 15" required 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">
                </div>
                <div>
                    <label for="parent_name" class="block text-sm font-medium text-gray-700 mb-1">اسم ولي الأمر</label>
                    <input type="text" name="parent_name" id="parent_name" placeholder="الاسم الكامل لولي الأمر" required 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">
                </div>
                <div>
                    <label for="parent_phone_1" class="block text-sm font-medium text-gray-700 mb-1">هاتف ولي الأمر 1 (مطلوب)</label>
                    <input type="tel" name="parent_phone_1" id="parent_phone_1" placeholder="مثال: 09xxxxxxxx" required 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">
                </div>
                <div>
                    <label for="parent_phone_2" class="block text-sm font-medium text-gray-700 mb-1">هاتف ولي الأمر 2 (اختياري)</label>
                    <input type="tel" name="parent_phone_2" id="parent_phone_2" placeholder="مثال: 09xxxxxxxx" 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">
                </div>
                <div>
                    <label for="student_phone" class="block text-sm font-medium text-gray-700 mb-1">هاتف الطالب (اختياري)</label>
                    <input type="tel" name="student_phone" id="student_phone" placeholder="مثال: 09xxxxxxxx" 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">
                </div>
                <div>
                    <label for="grade" class="block text-sm font-medium text-gray-700 mb-1">الصف</label>
                    <input type="text" name="grade" id="grade" placeholder="مثال: الصف العاشر" required 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">
                </div>
                <div>
                    <label for="school_name" class="block text-sm font-medium text-gray-700 mb-1">اسم المدرسة</label>
                    <input type="text" name="school_name" id="school_name" placeholder="مثال: مدرسة المستقبل" required 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">
                </div>
                <div class="md:col-span-2">
                    <label for="address" class="block text-sm font-medium text-gray-700 mb-1">العنوان</label>
                    <input type="text" name="address" id="address" placeholder="الشارع، المدينة" required 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">
                </div>
                <div class="md:col-span-2">
                    <label for="memorizing" class="block text-sm font-medium text-gray-700 mb-1">المحفوظات</label>
                    <input type="text" name="memorizing" id="memorizing" placeholder="مثال: القرآن، جزء عم" required 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">
                </div>
                <div class="md:col-span-2">
                    <label for="notes" class="block text-sm font-medium text-gray-700 mb-1">ملاحظات (اختياري)</label>
                    <textarea name="notes" id="notes" rows="3" 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"></textarea>
                </div>
                <div class="md:col-span-2">
                    <label for="registration_date" class="block text-sm font-medium text-gray-700 mb-1">تاريخ التسجيل (اختياري، الافتراضي هو اليوم)</label>
                    <input type="date" name="registration_date" id="registration_date" 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">
                </div>
            </div>
            <div class="mt-8 text-left">
                <button type="submit" id="submit-add-button" 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">
                    حفظ بيانات الطالب
                </button>
            </div>
        </form>
    </div>

    {# NEW: Button to toggle CSV Import section #}
    <div class="text-center mb-6">
        <button id="toggle-csv-import-button" class="px-6 py-2 bg-gray-300 text-gray-800 font-semibold rounded-lg shadow-md hover:bg-gray-400 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500 transition-all">
            استيراد من CSV
        </button>
    </div>

    {# WRAPPED: CSV Import section is now initially hidden #}
    <div id="csv-import-section" class="bg-white p-6 rounded-xl shadow-lg mb-8 hidden">
        <h2 class="text-2xl font-semibold mb-4 text-gray-800 border-b pb-4">استيراد من ملف CSV</h2>
        <div class="bg-yellow-50 border border-yellow-200 text-yellow-800 text-sm p-4 rounded-lg mt-4">
            <p class="font-bold">هام: تنسيق ملف CSV</p>
            <p>يجب أن يكون الملف بصيغة CSV ومرمّزاً بترميز UTF-8.</p>
            <p>يجب **ألا يحتوي** الملف على صف للعناوين، ويجب أن تكون الأعمدة بالترتيب الدقيق التالي:</p>
            <p class="mt-2" style="direction: ltr; text-align: right;">
                <code class="text-xs font-mono">اسم الطالب, العمر, اسم ولي الأمر, هاتف ولي الأمر 1, هاتف ولي الأمر 2, هاتف الطالب, الصف, اسم المدرسة, العنوان, المحفوظات, الملاحظات, تاريخ التسجيل</code>
            </p>
            <p>إذا كانت الحقول الاختيارية (هاتف ولي الأمر 2، هاتف الطالب، الملاحظات، تاريخ التسجيل) فارغة، اتركها كذلك. تاريخ التسجيل سيُعيّن تلقائياً لليوم الحالي إذا تُرِك فارغاً. **النقاط تبدأ من صفر ولا تُدرج في ملف CSV.**</p>
            <p class="mt-3">
                <a href="{{ url_for('download_csv_template') }}" class="text-blue-600 hover:underline font-semibold" download>
                    تنزيل قالب CSV
                </a>
            </p>
        </div>
        <div class="mt-6 text-left">
            <form id="import-form" action="{{ url_for('import_csv') }}" method="POST" enctype="multipart/form-data">
                <input type="file" name="file" id="csv-file-input" class="hidden" required accept=".csv">

                <button type="button" id="choose-file-button" class="px-6 py-2 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>

                <span id="file-name-display" class="hidden ml-4 text-gray-700"></span>

                <button type="submit" id="submit-import-button" class="hidden px-6 py-2 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">
                    تأكيد ورفع الملف
                </button>
            </form>
        </div>
    </div>

    <div class="bg-white p-6 rounded-xl shadow-lg">
        <div class="flex justify-between items-center mb-4 pb-4 border-b">
            <h2 class="text-2xl font-semibold text-gray-800">الطلاب المسجلون</h2>
            <button id="add-manually-button" class="px-6 py-2 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">
                إضافة يدوية
            </button>
        </div>

        <div class="mb-6">
            <label for="search-input" class="sr-only">البحث عن طالب</label>
            <input type="text" id="search-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">
        </div>

        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200 text-right">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">#</th>
                        <th class="px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">الإجراءات</th>
                        <th class="px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">اسم الطالب</th>
                        <th class="px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">العمر</th>
                        <th class="px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">ولي الأمر</th>
                        <th class="px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">أرقام التواصل</th>
                        <th class="px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">الصف</th>
                        <th class="px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">المدرسة</th>
                        <th class="px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">العنوان</th>
                        <th class="px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">المحفوظات</th>
                        <th class="px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">تاريخ التسجيل</th>
                        <th class="px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">ملاحظات</th>
                        <th class="px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">النقاط</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200" id="students-table-body">
                    {% for student in students %}
                    <tr class="hover:bg-gray-50 transition-colors duration-200">
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-bold text-gray-700">{{ loop.index }}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                            <a href="{{ url_for('modify_student', student_id=student['id']) }}" class="text-indigo-600 hover:text-indigo-900 mx-1">
                                <i class="fas fa-pen" title="تعديل"></i>
                            </a>
                            <a href="#" onclick="confirmDelete({{ student['id'] }}, '{{ student['student_name'] }}')" class="text-red-600 hover:text-red-900 mx-1">
                                <i class="fas fa-trash-alt" title="حذف"></i>
                            </a>
                            <form id="delete-form-{{ student['id'] }}" action="{{ url_for('delete_student', student_id=student['id']) }}" method="POST" style="display: none;"></form>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ student['student_name'] }}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600">{{ student['age'] }}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600">{{ student['parent_name'] }}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600">
                            <div class="flex flex-col">
                                <span>ولي الأمر 1: {{ student['parent_phone_1'] }}</span>
                                {% if student['parent_phone_2'] %}<span>ولي الأمر 2: {{ student['parent_phone_2'] }}</span>{% endif %}
                                {% if student['student_phone'] %}<span>الطالب: {{ student['student_phone'] }}</span>{% endif %}
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600">{{ student['grade'] }}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600">{{ student['school_name'] }}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600">{{ student['address'] }}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600">{{ student['memorizing'] }}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600">{{ student['registration_date'] }}</td>
                        <td class="px-6 py-4 text-sm text-gray-600 max-w-xs overflow-hidden text-ellipsis">{{ student['notes'] or 'لا يوجد' }}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-blue-700 font-semibold">{{ student['points'] }}</td>
                    </tr>
                    {% else %}
                    <tr id="no-students-row">
                        <td colspan="13" class="text-center py-6 text-gray-500">لم تتم إضافة أي طالب بعد.</td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
            <div id="no-search-results" class="text-center py-6 text-gray-500 hidden">
                لا توجد نتائج بحث مطابقة.
            </div>
        </div>
    </div>

    <script>
        const csvFileInput = document.getElementById('csv-file-input');
        const chooseFileButton = document.getElementById('choose-file-button');
        const fileNameDisplay = document.getElementById('file-name-display');
        const submitImportButton = document.getElementById('submit-import-button');
        const addManuallyButton = document.getElementById('add-manually-button');
        const addStudentSection = document.getElementById('add-student-section');
        const addStudentForm = document.getElementById('add-student-form');
        const submitAddButton = document.getElementById('submit-add-button');

        // NEW: CSV Import section and toggle button
        const csvImportSection = document.getElementById('csv-import-section');
        const toggleCsvImportButton = document.getElementById('toggle-csv-import-button');

        const searchInput = document.getElementById('search-input');
        const studentsTableBody = document.getElementById('students-table-body');
        const noStudentsRow = document.getElementById('no-students-row');
        const noSearchResultsDiv = document.getElementById('no-search-results');

        const allStudentData = [];
        studentsTableBody.querySelectorAll('tr').forEach(row => {
            if (row.id === 'no-students-row') {
                return;
            }
            allStudentData.push({
                element: row,
                student_name: row.children[2] ? row.children[2].textContent : '',
                parent_name: row.children[4] ? row.children[4].textContent : '',
                originalStudentNameHTML: row.children[2] ? row.children[2].innerHTML : '',
                originalParentNameHTML: row.children[4] ? row.children[4].innerHTML : ''
            });
        });

        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 highlightText(text, term) {
            if (!term) return text;
            const escapedTerm = term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
            const regex = new RegExp(escapedTerm, 'gi');
            return text.replace(regex, match => `<span class="highlight">${match}</span>`);
        }

        function filterStudents() {
            const searchTerm = searchInput.value.trim();
            let foundResults = 0;

            if (noStudentsRow) {
                noStudentsRow.classList.add('hidden');
            }

            if (searchTerm === '') {
                allStudentData.forEach(data => {
                    data.element.classList.remove('hidden');
                    if (data.element.children[2]) {
                        data.element.children[2].innerHTML = data.originalStudentNameHTML;
                    }
                    if (data.element.children[4]) {
                        data.element.children[4].innerHTML = data.originalParentNameHTML;
                    }
                });
                noSearchResultsDiv.classList.add('hidden');
                if (noStudentsRow && allStudentData.length === 0) {
                    noStudentsRow.classList.remove('hidden');
                }
                return;
            }

            allStudentData.forEach(data => {
                const studentName = data.student_name;
                const parentName = data.parent_name;

                const isMatch = fuzzyMatch(searchTerm, studentName) || fuzzyMatch(searchTerm, parentName);

                if (isMatch) {
                    data.element.classList.remove('hidden');
                    foundResults++;

                    if (data.element.children[2]) {
                        data.element.children[2].innerHTML = highlightText(studentName, searchTerm);
                    }
                    if (data.element.children[4]) {
                        data.element.children[4].innerHTML = highlightText(parentName, searchTerm);
                    }
                } else {
                    data.element.classList.add('hidden');
                    if (data.element.children[2]) {
                        data.element.children[2].innerHTML = data.originalStudentNameHTML;
                    }
                    if (data.element.children[4]) {
                        data.element.children[4].innerHTML = data.originalParentNameHTML;
                    }
                }
            });

            if (foundResults > 0) {
                noSearchResultsDiv.classList.add('hidden');
            } else {
                noSearchResultsDiv.classList.remove('hidden');
            }
        }

        searchInput.addEventListener('input', filterStudents);

        chooseFileButton.addEventListener('click', () => {
            csvFileInput.click();
        });

        csvFileInput.addEventListener('change', () => {
            if (csvFileInput.files.length > 0) {
                const fileName = csvFileInput.files[0].name;
                fileNameDisplay.textContent = `الملف المختار: ${fileName}`;
                fileNameDisplay.classList.remove('hidden');
                submitImportButton.classList.remove('hidden');
                chooseFileButton.classList.add('hidden');
            } else {
                fileNameDisplay.classList.add('hidden');
                submitImportButton.classList.add('hidden');
                chooseFileButton.classList.remove('hidden');
            }
        });

        addManuallyButton.addEventListener('click', () => {
            addStudentSection.classList.toggle('hidden');
            // Hide CSV import section if manual add is shown
            csvImportSection.classList.add('hidden');
            toggleCsvImportButton.textContent = 'استيراد من CSV'; // Reset button text
        });

        // NEW: Toggle CSV Import section visibility
        toggleCsvImportButton.addEventListener('click', () => {
            csvImportSection.classList.toggle('hidden');
            // Hide manual add section if CSV import is shown
            addStudentSection.classList.add('hidden');
            // Update button text based on visibility
            if (csvImportSection.classList.contains('hidden')) {
                toggleCsvImportButton.textContent = 'استيراد من CSV';
            } else {
                toggleCsvImportButton.textContent = 'إخفاء استيراد CSV';
            }
        });


        importForm.addEventListener('submit', () => {
            submitImportButton.disabled = true;
            submitImportButton.textContent = 'جاري الرفع...';
        });

        addStudentForm.addEventListener('submit', () => {
            submitAddButton.disabled = true;
            submitAddButton.textContent = 'جاري الحفظ...';
        });

        function confirmDelete(studentId, studentName) {
            if (confirm(`هل أنت متأكد أنك تريد حذف الطالب "${studentName}"؟ هذا الإجراء لا يمكن التراجع عنه.`)) {
                document.getElementById(`delete-form-${studentId}`).submit();
            }
        }
    </script>
{% endblock %}
